Archived

This topic is now archived and is closed to further replies.

Rian

int -> char*

Recommended Posts

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?

Share this post


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

Share this post


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

Share this post


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

Share this post


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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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;
}

Share this post


Link to post
Share on other sites