C++ Int to String by using ostringstream or stringstream

13,128

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.

Share:
13,128
Malkavian
Author by

Malkavian

Updated on June 25, 2022

Comments

  • Malkavian
    Malkavian almost 2 years

    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;
    
  • Malkavian
    Malkavian over 12 years
    Thank you so much!, I'll definitely try the methods you mentioned.
  • Drew Delano
    Drew Delano over 12 years
    I 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 the ostringstream technique. See The String Formatters of Manor Farm.
  • Seth Carnegie
    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
    Drew Delano over 12 years
    @SethCarnegie: Oh, perhaps. That would be a great idea.
  • Michael Kristofik
    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
    ildjarn over 12 years
    Boost.Spirit has the title of "fastest", but it comes with a not-insignificant compile-time cost. Boost.LexicalCast just wraps around snprintf.
  • Benjamin Lindley
    Benjamin Lindley over 12 years
    Boost.LexicalCast's number to string conversions are okay, but their string to number conversions are pretty terrible.
  • Catalyst
    Catalyst almost 10 years
    std::string str(itoa(numberVar,tempChars,10));