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.
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.
October 13, 2006 at 4:13 pm |
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();
}
July 3, 2007 at 5:34 am |
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++
July 3, 2007 at 5:35 am |
btw, awesome blog. love every bit of it
July 3, 2007 at 10:34 am |
Thanks for the comment!
February 25, 2008 at 8:56 pm |
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.
February 26, 2008 at 11:04 am |
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.”
July 21, 2008 at 7:29 am |
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);
September 12, 2008 at 12:36 am |
[...] פשוט! שחיפשתי בגוגל על המרה ממספר למחרוזת, הסתמכתי על תגובה של מישהו שכתב איך לדעתו C++ צריכה להיות כתגובה לפוסט של [...]
January 4, 2009 at 6:54 pm |
Thanks for sharing
this is elegant and simple solution
February 19, 2009 at 7:24 am |
What if I have to concatenate a string with an int using CComBSTR?