Dave's Brain

Browse - Programming Tips - Can I use CString's Format to create a string?

Date: 2012apr5
Framework: MFC
Language: C++

Q.  Can I use CString's Format to create a string?

A.  Its too bad that CString::Format() isn't static.
I would be nice if we could do:

CString str = CString::Format("number=%d", number); // DOES NOT WORK
as Java supports. But instead we have to do:
CString str; str.Format("number=%d", number); // Works but ugly
Here's a solution, use this function:
CString CStringFormat(LPCTSTR format, ...) { va_list ap; CString str; va_start(ap, format); str.FormatV(format, ap); va_end(ap); return str; }
Now you can do:
CString str = CStringFormat("number=%d", number); // Works and pretty

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.