How to convert an int to string in C? How to convert an int to string in C? c c

How to convert an int to string in C?


You can use sprintf to do it, or maybe snprintf if you have it:

char str[ENOUGH];sprintf(str, "%d", 42);

Where the number of characters (plus terminating char) in the str can be calculated using:

(int)((ceil(log10(num))+1)*sizeof(char))


EDIT: As pointed out in the comment, itoa() is not a standard, so better use sprintf() approach suggested in the rivaling answer!


You can use itoa() function to convert your integer value to a string.

Here is an example:

int num = 321;char snum[5];// convert 123 to string [buf]itoa(num, snum, 10);// print our stringprintf("%s\n", snum);

If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.


The short answer is:

snprintf( str, size, "%d", x );

The longer is: first you need to find out sufficient size. snprintf tells you length if you call it with NULL, 0 as first parameters:

snprintf( NULL, 0, "%d", x );

Allocate one character more for null-terminator.

#include <stdio.h> #include <stdlib.h>int x = -42;int length = snprintf( NULL, 0, "%d", x );char* str = malloc( length + 1 );snprintf( str, length + 1, "%d", x );...free(str);

If works for every format string, so you can convert float or double to string by using "%g", you can convert int to hex using "%x", and so on.