Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » Convert int to char*

This thread is locked; no one can reply to it. rss feed Print
Convert int to char*
Calle Arnesten
Member #1,356
April 2001

How do I in C++ convert integers to char*?
Say I have a number 123 I want it to be "123".
I searched the forum and what I found was something about sprintf, but that is C, and I also found someone mentioning itoa and _itoa, but I couldn't find those in my gcc compiler.
So is there another way?

lwithers
Member #630
September 2000

You could either write your own routine (which isn't difficult), or you could use the C library's sprintf() (there is nothing wrong with using libc calls in C++).
Here is an example of a function that returns a string class given an integer:
code:#include <string>
#include <stdio.h>
string int_to_string(int i)
{
char buf[100];
usprintf(buf, "%d", i);
return string(buf);
}
Note that I have used usprintf, which is Allegro's Unicode-aware version of sprintf. Also note that the C++ string class can handle the \0 character within strings, since it stores the length separately: this makes it valid to handle Unicode strings with string.

Jason Heim
Member #484
June 2000

careful!
you can get into trouble returning pointers to locally declared variables and arrays. this function would be better off receiving a pointer to a target array and returning nothing:
code:
void int_to_string(int i, char *c){
usprintf(c, "%d", i);
}

of course in this case, it is even better handled by a macro:
code:
#define int_to_string(i, c) usprintf(c, "%d", i)

good luck!

brain21
Member #1,208
December 2000

What about just using the itoa() command?
#include <stdio.h>
#include <string.h>
char string[]="90236";
int num;
num=itoa(string);

Jason Heim
Member #484
June 2000

brain21,

you mean atoi(), which converts the other way :)

i've never heard of itoa(), not to say that it doesn't exist, but it all probably uses the same routines behind the scenes (although sprintf would obscure it a little). the C reference i have doesn't list itoa(), only atoi().

good luck!

Bob
Free Market Evangelist
September 2000
avatar

itoa() is present in DJGPP, but it's listed as non-Ansi, non-Posix, so chances are it won't work on other compilers.

[ May 30, 2001: Message edited by: Bob ]

--
- Bob
[ -- All my signature links are 404 -- ]

Go to: