itoa and string variables

Started by
5 comments, last by Zahlman 18 years, 10 months ago
I want to convert a number to a string itoa works with char*s and it is kind of a pain to convert everything from char*s to strings. Is there a better way to do it?
Advertisement
Hi,

You can do the following i believe,

std::string myString = "15";

int ret = itoa( &myString[0] );

Give that a go.

ace
Don't use itoa(), it is not ANSI, and not implemented on all the platforms.
Use sprintf
somethign like sprintf(str,"%i",number);
The best way in C++ is to use boost::lexical_cast:
std::string something = lexical_cast<std::string>(1234);
Edit: I'm a moron. Proceed with correct suggestions

[Edited by - skulldrudgery on June 24, 2005 1:48:28 AM]
skulldrudgery--A tricky bit of toil
Quote:Original post by ace_lovegrove
std::string myString = "15";
int ret = itoa( &myString[0] );


That's atoi, and the correct way with a std::string would be atoi( myString.c_str() );

If you want itoa (integer->ascii) and using std::strings try using std::ostringstream
std::ostringstream ss;ss << num;std::string theStr = ss.str();
Not sure why the conversion to string from char* is such a pain, but you really should be doing it in one of the suggested ways anyway - preferably with boost::lexical_cast, which is a general-purpose wrapper around the stringstream manipulation that will check for a few weird corner cases that come up when you try to make it really general :)

This topic is closed to new replies.

Advertisement