Sign in to follow this  
MikeDee

int to *char [C++]

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

#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]

Share this post


Link to post
Share on other sites
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 ! :)

Share this post


Link to post
Share on other sites
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 ;)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this