Boost::format string examples

By , last updated November 21, 2015

Once boost::format object has been created with a format string and given arguments, there are two ways of getting a std::string (or std::wstring) from it. One is with boost::str() and the other way is with str() member method.

Read also: Boost::format dates, time, horizontal alignment


To begin with, we need to include the format library header. Create a format object. This is done by giving boost::format a string as the first argument.

#include <boost/format.hpp>

// Create a boost::format object, 
boost::format formatobject("Pi is %4.2f");

Feed the format object with a value. Boost::format will remember the value and format it later:

// Feed it with Pi
formatobject % 3.14;

At this point the format object has enough information to create a string for us. Just call either of boost::str() or formatobject.str().

// Get strings
std::string str1 = boost::str(formatobject);
std::string str2 = formatobject.str();

Now you can use str1 and str2 as a regular string with the value Pi is 3.14.

Read also: Boost::format numbers (int, float, double)


From here on it is easy to create a c-string. Remember the pointer is only valid as long as str1 is valid.

// Character array from the first string
const char * char1 = str1.c_str();

Read also: 5 Great things about Boost

Const std::string

It is also possible to exploit a lesser known feature of C++, specially when dealing with large strings. To avoid the cost of copying the string, it is perfectly legal to use a const reference. This is also known as The most important const. Details can be found here:

const std::string & str3 = boost::str(formatobject);
const std::string & str4 = formatobject.str();

The full example is available on Github.

Professional Software Developer, doing mostly C++. Connect with Kent on Twitter.


Be the first to comment.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>