Convert an int to a string.

closed account (G854izwU)
Hey guys I was wondering how you can convert an int to a string. Thanks for the help in advance!

-TheNewKid-
C++98 solution:
1
2
3
stringstream ss;
ss << integer;
string str=ss.str();


C++11 solution:
string str=to_string(integer);

Boost solution:
string str=lexical_cast<string>(integer);
closed account (G854izwU)
Thanks!
closed account (S6k9GNh0)
Alternative Boost solution based on Spirit:
string str=coerce_cast<string>(integer);

coerce_cast is a drop-in replacement for lexical_cast and is often many times faster than a streams-based solution. It's not in Boost by default and can be found in the sandbox. *sadface*
Last edited on
I'd like to point out that lexical_cast is already quite fast, about 6-7 times faster than when using the GNU implementation of std::stringstream for integer conversion.

And that is with boost 1.46. According to the changelog, the performance of lexical_cast has improved further in 1.47 and 1.48. However, it's still possible to do better. The version I'm using is about twice as fast as lexical_cast.
Last edited on
Topic archived. No new replies allowed.