5

This is a bit verbose to 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 using a concise one-line statement perhaps with templates or macros?

alexm
  • 6,854
  • 20
  • 24

2 Answers2

3

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)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
-6

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

EDIT

Looks like I didn't read my own link. So again you have a three line code. You could always define the following

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

Then you can just use the + operator to concat strings.

string msg("Selected elements: " + itostr(i) + "," + itostr(j) + ".");
dconman
  • 90
  • 3