C++ Formatting Strings

This topic is 2377 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I know there are the stringstream classes, which I can use to convert integers, floats, etc into strings, but this is not the same as the C formatting functions of C#'s string.Format method which work with variable number of arguments. Is there a C++ way for this, or should I just use _vsntprintf_s?

Share on other sites
You could try boost::format, which allows you to write things like cout << format("%2% %1%") % 36 % 77;

Share on other sites
The C++ string formatting facilities have many, many distinct advantages over the printf-style string formatting of C and similar. Type safety and speed are among the traits you do not find the printf-style facilities. Buffer overflows are something you miss with the C++ facilities.

The C++ string formatting facilities lack some of the brevity and succinctness of the printf-style facilities, but are in the long run more readable by others. the C++ facilities are useless and utterly to be avoided when it comes to internationalization. I can't believe the C++ standards committee did not fix this in C++2011.

I strongly recommend the boost format library for C++. It supports internationalization and has the type safety of the C++ facilities but the bass-ackward way of separating format from arguments that many prefer. It's slower than all the other choices, but most of the time when dealing with formatted strings, the I/O wait is orders of magnitude more expensive anyway.

Share on other sites
It's very handy to write your own std::string strprintf(const char *fmt, ...); function. You can make it work by using the return code of snprintf to see how large a buffer you would need to allocate, after which you snprintf into that and then construct a std::string. Or you maybe you could save a copy if you have your own string type.

You should also annotate it with the appropriate attribute so that your compiler can check the argument types.

Edit: Actually, you'll want to use vsnprintf, obviously, and you'll have to use va_copy, and I don't know if that's supported by MS VC++. Oh well!

Share on other sites
Hidden

I know there are the stringstream classes, which I can use to convert integers, floats, etc into strings, but this is not the same as the C formatting functions of C#'s string.Format method which work with variable number of arguments.

Don't forget that stringstreams can also be used to format strings, not necessarily to convert to and from types:

 ostringstream ss; ss << "Sample table\n" << string( 25, '-' ) << setw( 12 ) << left << "Row: " << fixed << setprecision(2) << 12.345 << endl; ; cout << ss.str() << endl; 
 Sample table ------------------------- Row: 12.34