C++ Int to String by using ostringstream or stringstream

13.7k views Asked by At

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;
1

There are 1 answers

8
Seth Carnegie On BEST ANSWER

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.