How to convert an integer to a character array using C

I want to convert an integer 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?

+7
source share
5 answers

use the log10 function to determine the number of digits and follow these steps

 char * toArray(int number) { int n = log10(number) + 1; int i; char *numberArray = calloc(n, sizeof(char)); for ( i = 0; i < n; ++i, number /= 10 ) { numberArray[i] = number % 10; } return numberArray; } 

or another sprintf(yourCharArray,"%ld", intNumber); option sprintf(yourCharArray,"%ld", intNumber);

+13
source

' sprintf ' will work fine if your first argument is a pointer to a character (the pointer to the character is an array in 'c'), you will need to make sure that you have enough space for all digits and end with '\ 0'. For example, if an integer uses 32 bits, it has up to ten decimal digits. Therefore, your code should look like this:

 int i; char s[11]; ... sprintf(s,"%ld", i); 
+9
source

An easy way is to use sprintf . I know others suggested itoa , but a) it is not part of the standard library, and b) sprintf provides formatting options that itoa does not support.

+1
source

You can take a picture by using itoa . Another alternative is to use sprintf .

0
source

Use itoa as shown here .

 char buf[5]; // convert 123 to string [buf] itoa(123, buf, 10); 

buf will be a string array as you document it. You may need to increase the size of the buffer.

0
source

All Articles