对我来说,这有点啰嗦:
ostrstream ss;
ss << "Selected elements: " << i << "," << j << ".";
string msg(ss.str(), (size_t)ss.pcount());
有没有一种简洁的方式来使用模板或宏格式化文本消息?
对我来说,这有点啰嗦:
ostrstream ss;
ss << "Selected elements: " << i << "," << j << ".";
string msg(ss.str(), (size_t)ss.pcount());
const int i = 3, j = 4;
const std::string msg = (boost::format("Selected elements: %d %d") % i % j).str();
(现场演示)
您最有可能需要的是sprintf,它类似于printf,但返回一个C字符串。因此,您的代码将是string msg(sprintf( "Selected elements: %d, %d.", i, j ) )
编辑
看起来我没有读自己的链接。所以你有三行代码。您始终可以定义以下内容
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) + ".");
sprintf
会将结果输出到它的第一个参数中,而你的第一个参数应该是一个常量格式字符串。 - v.oddoustd::sprintf()
。 - πάντα ῥεῖ