int to char* conversion

Y

Ying Yang

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.


Regards
weeeeee
 
K

Kevin Goodsell

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.

Since there is no implicit conversion, type casting is the only way.
Anyway, I'm looking for just a single
line statement, which can do this.

char *cp = reinterpret_cast<char *>(some_int);

However, this is usually not safe.

-Kevin
 
K

Kevin Goodsell

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::eek: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::eek: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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top