C++ Int to String by using ostringstream or stringstream
There is a third that you didn't mention, istringstream
, which you can't use (well you could but it would be different, you can't <<
to an istringstream
).
stringstream
is both an ostringstream
and an istringstream
- you can <<
and >>
both ways, in and out.
With ostringstream
, you can only go in with <<
, and you cannot go out with >>
.
There isn't really a difference, you can use either way to convert strings to integers. If you want to do it the fastest way possible, I think boost::lexical_cast
has that title, or you could use the itoa
function which may be faster than stringstream
, but you lose the advantages of C++ and the standard library if you use itoa
(you have to use C-strings, etc).
Also, as Benjamin Lindley informed us, C++11 has the ultramagical std::to_string
.
Malkavian
Updated on June 25, 2022Comments
-
Malkavian almost 2 years
I've been using
stringstream
to convertInteger
toString
, but then I realized same operation can be done withostringstream
.When I use
.str()
what is the difference between them? Also, is there more efficient way to convert integers to strings?Sample code:
//using ostringstream ostringstream s1; int i=100; s1<<i; string str_i=s1.str(); cout<<str_i<<endl; //using stringstream stringstream s2; int i2=100; s2<<i2; string str_i2=s2.str(); cout<<str_i2<<endl;
-
Malkavian over 12 yearsThank you so much!, I'll definitely try the methods you mentioned.
-
Drew Delano over 12 yearsI think
boost::lexical_cast
is great, but it's probably not the best in terms of run-time performance. It's just a wrapper around theostringstream
technique. See The String Formatters of Manor Farm. -
Seth Carnegie over 12 years@FredLarson I thought boost did some specialisation for integers or something that made it faster. Maybe I just misread something somewhere.
-
Drew Delano over 12 years@SethCarnegie: Oh, perhaps. That would be a great idea.
-
Michael Kristofik over 12 years@FredLarson, I don't think that's necessarily true anymore. As of Boost 1.48.0, there is way more code in there than just a simple wrapper around a
stringstream
. -
ildjarn over 12 yearsBoost.Spirit has the title of "fastest", but it comes with a not-insignificant compile-time cost. Boost.LexicalCast just wraps around
snprintf
. -
Benjamin Lindley over 12 yearsBoost.LexicalCast's number to string conversions are okay, but their string to number conversions are pretty terrible.
-
Catalyst almost 10 yearsstd::string str(itoa(numberVar,tempChars,10));