You can use this function as an alternative to itoa. It’s only half as good as itoa because you can’t specify the base of your number to be converted.
sprintf takes three arguments.
The first has to be a char * variable, which means you can use a char array, but make sure it’s big enough to hold the converted number.
The second argument is a string containing a format specifier, depending on the format of the number you want to convert.
The third argument is the number you want to convert into a string.
sprintf returns the number of characters in the string (not included the null character).
This example convert a few numbers into string format, and prints out the result:
#include "stdio.h"
int main() {
char str[10];
int i;
i = sprintf(str, "%o", 15);
printf("15 in octal is %s\n", str);
printf("sprintf returns: %d\n\n", i);
i = sprintf(str, "%d", 15);
printf("15 in decimal is %s\n", str);
printf("sprintf returns: %d\n\n", i);
i = sprintf(str, "%x", 15);
printf("15 in hex is %s\n", str);
printf("sprintf returns: %d\n\n", i);
i = sprintf(str, "%f", 15.05);
printf("15.05 as a string is %s\n", str);
printf("sprintf returns: %d\n\n", i);
return 0;
}