Question

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

Was it helpful?

Solution

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!

OTHER TIPS

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);

FormatString - smart string formatting
By Ivo Beltchev

Posted on CodeProject

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top