How do you convert an int
(integer) to a string? I\'m trying to make a function that converts the data of a struct
into a string to save it in a fi
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
#include
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.