convert int to string

Started by
26 comments, last by biscuitz 17 years, 8 months ago
How do I convert an int into a string?
Advertisement
In what language?
C/C++, win32
You can either use boost::lexical_cast or a std::stringstream.
std::stringstream sstr;sstr << my_int;std::string str1 = sstr.str();std::string str2 = boost::lexical_cast<std::string>(my_int);
:) Thanks
std::string str = itoa(2342348);

Alternatively you can use atoi to convert back. I believe there are other C methods like atof and ftoa (f = float, i = int, a = *char .. XtoY())
itoa() isn't a standard C or C++ function, so there's no guarantee that a given C++ compiler will have it. Even if a C++ compiler has it, then there's no guarantee that the function will have the same function signature as the version you posted (most won't). On the compilers that do have a function signature that matches the version you just used, the code you posted may leak memory, as the return value will need to be free()'d.

itoa: just say no.
Well, some do. If they do then take advantage of it I say.

Also, because the net here is so slow it took a while to come up with an example. (I don't use itoa that often, if ever)
char buffer [33];
std::string str = itoa (41515,buffer,10);

10 is the base, so if you wanted Hex you'd use 16 or binary would be base 2.


SiCrane: Yeah, I knew that would give a leak. That's why I searched for an example. This one shouldn't give a memeory leak.
Also boost isn't standard C\C++ either, so were on the same page. [grin]
:S I tried using itoa with TextOut() and comes up with a bunch of characters on the end (which I don't want to show up) Ima try std strings.
Quote:Original post by PumpkinPieman
Also boost isn't standard C\C++ either, so were on the same page. [grin]


There's only one boost::lexical_cast. There are at least eight different versions of itoa() out there. That's hardly the same page.

This topic is closed to new replies.

Advertisement