Hello all. I am new to C programming and was wondering if it is possible to convert an integer value to char or string. I checked a book, but only found documentation to convert from string to integer. Thanks in advance.
A char is an integer type already.
sprintf
int to char is done by simply casting:
int i = 10; char c; c = i;
Remember that chars can hold 256 numbers only. As for string, just use sprintf, like sprintf(buffer, "%d", i);, where buffer is a char array and i an integer. Remember to make the buffer as large as necessary.
If you want to convert from an integer to a string with a specified radix, use itoa().
itoa()
Thanks for the help. If I were adding the numeric value to the end of an existing string, would the format be:
char buffer[16} = "<some characters>";
int place;
char c;
c = sprintf(buffer, "%d", place);?
[/edit] I tried itoa, got an undefined reference to itoa.
[edit/]
That worked. Thanks LennyLen and X-G.
[\edit] Oops, closed the thread too soon. It appears to be overwriting what is in buffer, as opposed to adding place to the end. Any ideas?
[\edit]
I tried itoa, got an undefined reference to itoa
You need to add the following to the top of your code:
#include <stdlib.h>
<stdlib.h> was included. Is it recent? Maybe my compiler does not support it yet.
It's not new, but it's not an ANSI C funtion either, though most compilers support it. Which are you using?
The following compiled fine for me using GCC.
I am using gcc 4.0.2. I copied the test program you submitted and compiled, still having problems with the itoa function. Are you coding in C or C++? I coded in C.
I compiled as C. I'm currently using GCC 3.4.2, so perhaps it's been removed in later versions.
New rule: no creating new programming forum threads until you read the thread list!
Is this week the printf assignment at the college that you three attend?
http://www.allegro.cc/forums/thread/588773
http://www.allegro.cc/forums/thread/588701
Not that I'm being hostile or anything.
CGamesPlay: My origional question was how to convert an int to char or string. To get back on topic, I tried sprintf, the new characters overwrote what was in the target string. Is there any way to add the characters to the end of the string, or did I do something wrong?
That was it. Thanks.