In my application, I will be retrieving error message strings from a database. I would like to substitute numbers into the error message. The error message will be a C style string like:
Message %d does not exist
or
Error reading from bus %d
Ideally, I would like to be able to do a C style printf using this statement, and substituting my own numbers in. I know I can just do it manually, but is there an easier way to somehow use it like a string in a regular printf?
Apart for simple string concatenation or using <<
together with number and a message.
I can think of 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";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.