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?
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?
Make use of the log10
function to determine the number of digits and do like below:
char * toArray(int number)
{
int n = log10(number) + 1;
int i;
char *numberArray = calloc(n, sizeof(char));
for (i = n-1; i >= 0; --i, number /= 10)
{
numberArray[i] = (number % 10) + '0';
}
return numberArray;
}
Or the other option is sprintf(yourCharArray,"%ld", intNumber);
floor()
is necessary around log10(number)
to avoid rounding error... but I'm not sure... anyways +1 good answer
for ( i = n-1; i >= 0; --i, number /= 10 )
so the output isn't reversed and the line in the loop to be numberArray[i] = (number % 10)+'0';
to convert the int to a char.
Sep 23, 2020 at 5:34
'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);
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.
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.
itoa
is not a standard C function, it will not be present on all implementations.
using namesapce std;
for instance. en.cppreference.com/w is a community managed reference, as accurate if not more, and without the poor habits in the examples.
Jan 28, 2013 at 15:10