int to *char [C++]

Started by
4 comments, last by phresnel 14 years, 8 months ago
It's a pretty straitforward question, how do I convert a int to a char* or string (in C++) ? I googled but amazingly I couldn't find anything relevant.
Advertisement
Your google-fu needs some work. "int to std::string C++" turns up hundreds of thousands of results.


Anyway, the solution is,
#include <sstream>int i = 42;std::string s;std::stringstream out;out << i;s = out.str();


Or you can use C's itoa() function.
#include <sstream>int main(){   int n = 42;   std::string str;   std::ostringstream ss;   ss << n;   str = ss.str();   return 0;}


EDIT: Bah, too slow

[Edited by - Evil Steve on August 19, 2009 7:37:00 AM]
ahah thanks guies, it solved my problem.

choffstein, I tried searching "int to std::string C++" and google only came up with two results. :P

Thanks a bunch anyway ! :)
Try it without the quotes.
Quote:Original post by MikeDee
ahah thanks guies, it solved my problem.

choffstein, I tried searching "int to std::string C++" and google only came up with two results. :P

Thanks a bunch anyway ! :)


Also note that "int to char*" is a bit smeary if you don't intend to take the value of an integer as an address of type pointer to char 0, but to convert it to a string.


0 this was actually my first thought, the solution would have involved type punning or so, leading you into the completely false direction. Luckily I scrolled down first ;)

This topic is closed to new replies.

Advertisement