C++ — Convert int to string

by

In order to convert an int (or any other numeric type, e.g., float, double, etc.) to string, you can use:

#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

Other C/C++ not so frequently asked questions.

About these ads

24 Responses to “C++ — Convert int to string”

  1. radu Says:

    Here’s a more generic version:

    #include <sstream>

    template <class T>
    inline std::string to_string (const T& t)
    {
    std::stringstream ss;
    ss << t;
    return ss.str();
    }

  2. djvishnu Says:

    ah, finally a smart way of doing this! Thank you!

    I’m sick and tired of

    sprintf(buf, “somestring_%i”,counter++);
    string name(buf);

    which neither generic, readable nor .. c++

  3. djvishnu Says:

    btw, awesome blog. love every bit of it

  4. rvernica Says:

    Thanks for the comment!

  5. thebirdiehaswings Says:

    Hey. Great blog!

    One question though, why does the string variable have to be named str?
    I tried a different variable name and surprisingly it doesn’t work.

  6. rvernica Says:

    Thanks for the comment!

    We updated the entry and now we use a different name for the string variable, as “str” is also a member of “stringstream.”

  7. dhjdhj Says:

    I wonder why the implementation of std::string doesn’t include automatic conversion from the standard primitives so that one could continue the pretense that C+ is really an OO language (grin)

    Seriously though,

    one should be able to write

    std::string foo = 123
    or even

    std:: string foo;
    foo.ToInt(123);

  8. dusanbole Says:

    Thanks for sharing
    this is elegant and simple solution

  9. pablito900 Says:

    What if I have to concatenate a string with an int using CComBSTR?

  10. How to convert an int to a string in C++? (Also doubles, floats, etc…) « Rhyous's 127.0.0.1 or ::1 Says:

    [...] I found a comment on another guys blog that actually makes it work for any type such as double, float, etc.. It has this code using this template. http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/ [...]

  11. kr1zz Says:

    Thank you :-)
    Nice blog!

  12. sdpagent Says:

    Thanks i needed that. Not sure if anyone’s stated this but would only really work uniquely if you keep your integers between -127 and 127, otherwise you will not get a unique string, ie char only goes from -127 to 127 as it is one byte, whereas integer i believe is 2 bytes and goes 0 to 65535 or -32767 to 32767.
    I believe if you put in integer higher than 127 it just loops round to -127 and continues.

    • dathoedezt Says:

      @sdpagent
      have u tried?

      i believe its not limited to char type size since the stream takes each number in at a time, and each number is a char like it would read 512 as “(char)53 << (char)49 << (char)50", so dont have to worry about the size of the int or whatever.

  13. lkjoel Says:

    Thanks for the post!
    That solved my problem.

  14. Abdullah Aydın Says:

    This is not working babe.

  15. Anu Lavanya Says:

    hi,
    Its a very useful one..
    Though i have one question.. what if the integer value contained i as 000012( i=000012). the output it gives as 10.. please clarify why it is so!

  16. Anu Lavanya Says:

    Hey Rares.. Thank you so much!:)

  17. saulus (@saulutz) Says:

    #include

    string s = boost::lexical_cast( number );

    http://www.cplusplus.com/forum/beginner/7777/

  18. dchesler Says:

    Can this be used in a function? I’ve seen a claim that it can, as in
    return out.str();
    but isn’t that returning a (plain old, dumb) pointer to memory that is going out of scope?

    I’m storing a bunch of different data from a structure into something like an XML DOM, all string data. For now I have a bunch of overloads
    SaveData(whereToPutIt, int iValue);
    SaveData(whereToPutIt, double dValue);
    SaveData(whereToPutIt, char * szValue);
    so I can call
    SaveData(whereToPutIt, MyStructure.dataField).

    The overload for int does the conversion as above and calls the string overload. I’d like to concentrate all the conversions like
    SaveData(whereToPutIt, ToStr(MyStructure.dataField) );
    and not have all the overloads, because I think it would be more elegant, but I want neither of smart pointers (outside the magnitude of the task I’ve been given), pointers to orphans, or memory leaks. And some global buffer with a macro might make my employer discover that I’m a really a C programmer, not an OO C++ programmer.

  19. Господин Бонев Says:

    Thank you!!

  20. Thefourtheye Divi Says:

    Looks like we are sacrificing performance for simplicity…

  21. C++ ? Convert int to string | Not So Frequently Asked Questions Says:

    [...] FAQ, Tips & Tricks For Unix, Emacs And Other Useful Tools http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/ [...]

  22. Convert string to int and Reverse - Programming - Fclose Tutorials Says:

    […] http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/ […]

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: