I want to convert an integer number to a character array in C.
Input:
int num = 221234;
The result is equivalent to:
char arr[6];
arr[0] = '2';
arr[1] = '2';
arr[2] = '1';
arr[3] = '2';
arr[4] = '3';
arr[5] = '4';
How can I do this?
This question is related to
c
The easy way is by using sprintf
. I know others have suggested itoa
, but a) it isn't part of the standard library, and b) sprintf
gives you formatting options that itoa
doesn't.
'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'. For example, If an integer uses 32 bits, it has up to 10 decimal digits. So your code should look like:
int i;
char s[11];
...
sprintf(s,"%ld", i);
Use itoa, as is shown here.
char buf[5];
// Convert 123 to string [buf]
itoa(123, buf, 10);
buf
will be a string array as you documented. You might need to increase the size of the buffer.
Source: Stackoverflow.com