Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format string in boost library

Tags:

c++

boost

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.

like image 584
Neel Avatar asked Mar 09 '23 14:03

Neel


1 Answers

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.

like image 94
hnefatl Avatar answered Mar 20 '23 13:03

hnefatl