I want to format string with boost library in C++. I am doing as below.
std::string msg = "Version: %1. Version %2.";
boost::format formatter(msg.c_str());
formatter % "v1" % "v2";
xyz_function(msg);
We can do that with sprintf in one statement so is there a way to optimize above boost implementation for string formation in one statement or something other ?
Thanks in Advance.
A boost::format
object can be cast to a string and it also has an explicit conversion function.
boost::format fmt
= boost::format("Luke %1% and Han %2%.") % "Skywalker" % "Solo";
So either of these can be used:
std::string fmtStr = boost::str(fmt);
std::string fmtStr = fmt.str();
See example and demonstration, and Boost Library Format; getting std::string for the boost::str
tip.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With