在我的应用程序中,我将从数据库中检索错误消息字符串。我想将数字替换为错误消息。错误消息将是一个 C 风格的字符串,如:
Message %d does not exist
或者
Error reading from bus %d
理想情况下,我希望能够使用此语句执行 C 样式 printf,并替换我自己的数字。我知道我可以手动完成,但是有没有更简单的方法可以像常规字符串一样使用它打印?
除了简单的字符串连接或<<
与数字和消息一起使用。
我能想到boost::format
int message_no=5;
std::cout << boost::format("Message %d doesn't exist") % message_no ;
The C++ way is to use std::stringstream:
std::stringstream str;
str << "Message " << messageName << " doesn't exist";
std::string out = str.str();
There is also very nice header-only boost string algorithms library:
std::string message = "Message %s doesn't exist";
boost::replace_first( str, "%s", "MyMessage" );
// message == "Message MyMessage doesn't exist"
and boost::format
, which acts like printf, but is entirely type-safe and supports all user-defined types:
std::string out = format( "Message %1 doesn't exist" ) % "MyMessage";