#include <sstream> //include this to use string streams
int number = 1234;
std::ostringstream ostr; //output string stream
ostr << number; //use the string stream just like cout,
//except the stream prints not to stdout but to a string.
std::string theNumberString = ostr.str(); //the str() function of the stream
//returns the string.
//now theNumberString is "1234"
Note that you can use string streams also to convert floating point numbers to a string, and format the string as you wish, just like with
float f = 1.2;
int i = 3;
ostr << f << " + " i << " = " << f + i;
std::string s = ostr.str();
//now s is "1.2 + 3 = 4.2"
You can use stream manipulators like
std::hex and functions
std::setprecision() etc. with string streams just like with
Do not confuse
std::ostrstream. The latter is obsolete
Use boost lexical casting. If you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. You can download and install boost and its documentation here . Although boost is not part of the C ++ standard, many boost libraries are eventually standardized, and boost is widely regarded as one of the best C ++ libraries.
Lexical casting uses streams at the bottom, so this is basically the same as the previous one, only less verbose.
float f = 1.2;
int i = 42;
std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
std::string si = boost::lexical_cast<std::string>(i); //sf is "42"