Click to See Complete Forum and Search --> : int to char* conversion


Brian Budge
July 30th, 1999, 02:33 PM
Does anybody know of any standard C++ functions to convert an int to a char*?

Something that would take the number 9876 to {'9','8','7','6'}?

I would rather not reinvent the wheel if there is something like this already.

Thanks,
Brian Budge

ChristianM
July 30th, 1999, 02:37 PM
u can use itoa();

Eric Smith
July 30th, 1999, 02:40 PM
This isn't C++ specific, but...


int integer=9876;
char string[20]; // be big enough for the digits

sprintf(string,"%d",integer);

// string now contains "9876"

chiuyan
July 30th, 1999, 02:54 PM
The original poster was asking for a standard C++ function to convert an int to a char*, and _itoa is not standard, it is Microsoft specific. Some other compilers may support it, but it is not part of the standard library. If Brian Budge is only interseted in the Windows platform, itoa is fine, but it is not standard.

The more portable way to do this is as Eric Smith said, sprintf.

HTH
--michael

ChristianM
July 30th, 1999, 03:03 PM
yes .. its true.. i anwsered too fast..

Leila Melloto
July 30th, 1999, 03:07 PM
You can do:
char *str;
int nValor=9876;
str = new char ;
wsprintf(str,"%d",nValor);
Hope this help.
Leila

chiuyan
July 30th, 1999, 03:19 PM
you wouldn't want to do that. You are only allocating 1 byte, and then trying to write a 5 byte string into it. you would have to new a char array big enough to hold all the numbers.
str = new char [5]; // atleast 5.
and then delete it later. Of course if the length is constant
char str[5]
is better.

HTH
--michael