Preferred string formatting method in C ++?

This is a bit detailed for my taste:

ostrstream ss;
ss << "Selected elements: " << i << "," << j << ".";
string msg(ss.str(), (size_t)ss.pcount());

Is there an elegant way to format a text message with a brief one-line operator, perhaps with templates or macros?

+4
source share
2 answers

Yes; You are looking for Boost.Format :

const int i = 3, j = 4;
const std::string msg = (boost::format("Selected elements: %d %d") % i % j).str();

( live demo )

+2
source

What you are most likely looking for is sprintf , which works like printf but returns cstring.So your code will be string msg(sprintf( "Selected elements: %d, %d.", i, j ) ) Del>

EDIT

, . , .

std::string itostr( int i )
{
    char temp[20];
    std::sprintf( temp, "%d" i);
    std::string out(temp);
    return out;
}

+ .

string msg("Selected elements: " + itostr(i) + "," + itostr(j) + ".");
-6

All Articles