How to convert an int to string in C?

user1063999 picture user1063999 · Nov 24, 2011 · Viewed 826.6k times · Source

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 file.

Answer

cnicutar picture cnicutar · Nov 24, 2011

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))