int -> char*

Started by
5 comments, last by Rian 21 years, 7 months ago
This is driving me crazy: how do you convert a number to a string, without writing some stupid algorithm to map the individual digits to chars? I''m guessing there is some way to convert int to string to char*, but I have no documentation on the standard string include, so I don''t know how to do it. Is there any way to convert it with or with out using the string include? And while we''re on the subject, how do you convert string/char* to int? or string/char* to float?
I can imagine a world without hate, a world without fear, a world without war. And I can imagine us attacking that world, because they would never expect it. -Jack Handy
Advertisement
atoi converts from char* to int, itoa from int to char*, and sprintf can do what itoa does, plus works with lots of other types

[edited by - atcdevil on September 1, 2002 3:22:38 PM]
I generally use sprintf or std::stringstream, depending on my mood.

#include <string>using std::string;#include <stringstream>using std::stringstream;stringstream ss;ss << (int)1337;string cppstring=ss.str();const char* lpszHungarianissomuchfun=cppstring.c_str(); 


I''m hip because I say "M$" instead of "MS".
"There is only one everything"
quote:Original post by Rian
how do you convert a number to a string, without writing some stupid algorithm to map the individual digits to chars?


You don''t. Really. Even the standard library algorithms do that behind the scenes.
daerid@gmail.com
quote:Original post by atcdevil
atoi converts from char* to int, itoa from int to char*, and sprintf can do what itoa does, plus works with lots of other types

The ''itoa'' function is very non-standard, and should be avoided.
Great! Thanks. That will help a lot!
I can imagine a world without hate, a world without fear, a world without war. And I can imagine us attacking that world, because they would never expect it. -Jack Handy
Another way to do it is via the boost library''s lexical cast function. See http://www.boost.org/libs/conversion/lexical_cast.htm

Here is an example:
#include <iostream>#include <string>#include <vector>#include <boost/lexical_cast.hpp>using namespace std;using boost::lexical_cast;using boost::bad_lexical_cast;int main(int argc, char * argv[]){    vector<short> args;    while(*++argv)    {        try        {            args.push_back(lexical_cast<short>(*argv));        }        catch(bad_lexical_cast &        {            args.push_back(0);        }    }    while( args.size() )    {       try       {          cout << lexical_cast<string>(args.front());       }       catch(bad_lexical_cast &       {       }       args.pop_front();    }    return 0;} 

This topic is closed to new replies.

Advertisement