views:

1133

answers:

3

Is there any better alternative for doing string formatting in VC6, with syntax checking before substitution?

+7  A: 

CString offers the Format method for printf-style formatting, but this isn't type-safe.

For type-safe string formatting you could either use std::stringstream / std::wstringstream or the Boost Format library, although these both work with the C++ std::basic_string class template, and not the MFC CString class. I've used both of these successfully in VC6.

Boost Format is nice because it allows you to use printf-like syntax, and will throw an exception if the arguments you supply don't match the format string, whereas string formatting with C++ iostreams tends to make your code quite verbose.

Note that you can create a CString object from a std::string as follows:

std::string s;
CString str( s.c_str() );

I hope this helps!

ChrisN
can i use that with VC6
yesraaj
std::string and std::stringstream are both elements of the standard library. If you need wide-char variants, use std::basic_string<wchar_t> and std::basic_stringstream<wchar_t>. So: yes, VC6 compliant.
xtofl
Yes, these work with VC6. I've updated my answer.
ChrisN
A: 

FormatString - smart string formatting
By Ivo Beltchev

Posted on CodeProject

SAMills
+1  A: 

Check out FastFormat. It has an easy syntax, and a "sink" - FastFormat terminology for the thing that receives the result of the formatting operation - for CString.

Something along the lines of:

int i = 1;
std::string ss = "a std string";
CString cs = "a Cstring";

CString result;

fastformat::fmt(result, "i={0}, ss={1}, cs={2}", i, ss, cs);
dcw