C++ — Convert int to string

By Rares Vernica

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.

10 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. היכרות ראשונה עם CPPCMS» הבלוג של נדב ויניק Says:

    [...] פשוט! שחיפשתי בגוגל על המרה ממספר למחרוזת, הסתמכתי על תגובה של מישהו שכתב איך לדעתו C++ צריכה להיות כתגובה לפוסט של [...]

  9. dusanbole Says:

    Thanks for sharing
    this is elegant and simple solution

  10. pablito900 Says:

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

Leave a Reply

You must be logged in to post a comment.