C ++ Int to String using ostringstream or stringstream

I used stringstream to convert Integer to String , but then I realized that the same operation could be done with ostringstream .

When I use .str() , what is the difference between them? Also, is there a more efficient way to convert integers to strings?

Code example:

 //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; 
+4
source share
1 answer

There is a third that you did not mention, istringstream , which you cannot use (well, you could, but it would be different, you cannot << to istringstream ).

stringstream is both ostringstream and istringstream - you can << and >> in both directions, in and out.

With ostringstream you can only log in with << , and you cannot log out with >> .

Actually there is no difference, you can use any way to convert strings to integers. If you want to do this as quickly as possible, I think boost::lexical_cast has this header, or you can use the itoa function, which may be faster than stringstream , but you lose the benefits of C ++ and the standard library if you use itoa (you should use C-lines, etc.).

In addition, as Benjamin Lindley told us, C ++ 11 has an std::to_string .

+11
source

Source: https://habr.com/ru/post/1390116/


All Articles