Connecting Tech Pros Worldwide Forums | Help | Site Map

int to char* conversion

Ying Yang
Guest
 
Posts: n/a
#1: Jul 19 '05
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


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.510 / Virus Database: 307 - Release Date: 14/08/2003



Kevin Goodsell
Guest
 
Posts: n/a
#2: Jul 19 '05

re: int to char* conversion


Ying Yang wrote:
[color=blue]
> Hi,
>
> What is the simplest way of converting an int into a char*? I realized type
> casting did not work for some reason.[/color]

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

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

However, this is usually not safe.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Kevin Goodsell
Guest
 
Posts: n/a
#3: Jul 19 '05

re: int to char* conversion


Ying Yang wrote:[color=blue]
> 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.[/color]

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::ostringstream 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::ostringstream 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
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Closed Thread


Similar C / C++ bytes