I've been using stringstream
to convert Integer
to String
, but then I realized same operation can be done with ostringstream
.
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;
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 anistringstream
).stringstream
is both anostringstream
and anistringstream
- 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 theitoa
function which may be faster thanstringstream
, but you lose the advantages of C++ and the standard library if you useitoa
(you have to use C-strings, etc).Also, as Benjamin Lindley informed us, C++11 has the ultramagical
std::to_string
.