Ying said:
Hi,
What is the simplest way of converting an int into a char*? I realized type
casting did not work for some reason. Anyway, I'm looking for just a single
line statement, which can do this.
OK, because I'm bored, here's a real answer to the question I *think*
you meant to ask. In the future, you might want to try to state your
question more clearly.
The recommended way (i.e., don't use char *s at all - use std::strings
instead):
#include <sstream>
#include <string>
int main()
{
int some_int = 3028;
std:
stringstream sout;
sout << some_int;
std::string converted_string(sout.str());
}
The less recommended way (type safe, copying into a dynamically sized
array):
#include <sstream>
#include <cstring>
int main()
{
int some_int = 3028;
std:
stringstream sout;
sout << some_int;
char *buff = new char[sout.str().length() + 1];
std::strcpy(buff, sout.str().c_str());
// ... (use buff here)
delete [] buff;
}
The extremely unrecommended way (no type safety, writing into a
carefully sized array):
#include <climits>
#include <cstdio>
int main()
{
int some_int = 3028;
char array[(sizeof(int) * CHAR_BIT + 2) / 3 + 1 + 1];
std::sprintf(array, "%d", some_int);
}
See
http://www.eskimo.com/~scs/C-faq/q12.21.html for an explanation of
the size used for array.
-Kevin