Thursday, July 30, 2009

How do I convert an integer to a string in C++?

I just want to output an integer to a stream, but I need it to be a string and not an integer. Any ideas?

How do I convert an integer to a string in C++?
if its a variable, then you can typecast it to a string:





int a = 4;


string b = (string)a;





if its just a number, just put it in quotes:





string a = "4";
Reply:int sprintf(char *str, const char *format, ...);





so you would say:


sprintf(your_string_pointer, "%d", your_integer);
Reply:atoi, and sprintf are NOT C++!





Do not use C operations in C++, it is bad programming.





Use this:





template%26lt;class T%26gt;


std::string ToString(const T%26amp; val)


{


std::stringstream%26lt;char%26gt; strm;


strm %26lt;%26lt; val;


return strm.str();


}





This will convert ANY data type understood by the C++ stream into a string. This includes user defined types, structured types, and classes which have the '%26lt;%26lt;' operator defined.

jasmine

No comments:

Post a Comment