In this recipe, we will continue discussing the lexical conversions, but now we will be converting numbers to strings using Boost.LexicalCast
. As usual, boost::lexical_cast
will provide a very simple way to convert the data.
Let's convert integer 100
to std::string
using boost::lexical_cast
:
#include <cassert> #include <boost/lexical_cast.hpp> void lexical_cast_example() { const std::string s = boost::lexical_cast<std::string>(100); assert(s == "100"); }
Compare it against the traditional C++ conversion method:
#include <cassert> #include <sstream> void cpp_convert_example() { std::stringstream ss; // Slow/heavy default constructor. ss << 100; std::string s; ss >> s; // Variable 'ss' will dangle all the way, till the end // of scope. Multiple virtual methods and heavy //...