Converting int to string in C
Solution 1:
Use snprintf
, it is more portable than itoa
.
itoa is not part of standard C, nor is it part of standard C++; but, a lot of compilers and associated libraries support it.
Example of sprintf
char* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);
Example of snprintf
char buffer[10];
int value = 234452;
snprintf(buffer, 10, "%d", value);
Both functions are similar to fprintf
, but output is written into an array rather than to a stream. The difference between sprintf
and snprintf
is that snprintf
guarantees no buffer overrun by writing up to a maximum number of characters that can be stored in the buffer
.
Solution 2:
Use snprintf
- it is standard an available in every compilator. Query it for the size needed by calling it with NULL, 0
parameters. Allocate one character more for null at the end.
int length = snprintf( NULL, 0, "%d", x );
char* str = malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
...
free(str);
Solution 3:
Before I continue, I must warn you that itoa
is NOT an ANSI function — it's not a standard C function. You should use sprintf
to convert an int
into a string.
itoa
takes three arguments.
- The first one is the integer to be converted.
- The second is a pointer to an array of characters - this is where the string is going to be stored. The program may crash if you pass in a
char *
variable, so you should pass in a normal sized char array and it will work fine. - The last one is NOT the size of the array, but it's the BASE of your number - base 10 is the one you're most likely to use.
The function returns a pointer to its second argument — where it has stored the converted string.
itoa
is a very useful function, which is supported by some compilers - it's a shame it isn't support by all, unlike atoi
.
If you still want to use itoa
, here is how should you use it. Otherwise, you have another option using sprintf
(as long as you want base 8, 10 or 16 output):
char str[5];
printf("15 in binary is %s\n", itoa(15, str, 2));
Solution 4:
Better use sprintf(),
char stringNum[20];
int num=100;
sprintf(stringNum,"%d",num);
Solution 5:
Usually snprintf()
is the way to go:
char str[16]; // could be less but i'm too lazy to look for the actual the max length of an integer
snprintf(str, sizeof(str), "%d", your_integer);