This item was added on: 2003/01/28
One method to convert an int to a char array is to use sprintf() or snprintf(). This function can be used to combine a number of variables into one, using the same formatting controls as fprintf().
The prototypes:
#include <stdio.h>
int sprintf ( char *buf, const char *format, ... );
int snprintf( char *buf, size_t n, const char *format, ... );
The following example shows some of the ways it can be used.
#include <stdio.h>
int main(void)
{
int i = 12345;
char buf[BUFSIZ];
char name[] = "Hammer";
printf ("i is: %d\n", i);
snprintf(buf, sizeof(buf), "%d", i);
printf ("buf is now: %s\n", buf);
snprintf(buf, sizeof(buf), "%s %010d", name, i);
printf ("buf has changed to : %s\n", buf);
return(0);
}
Or, here's the same thing done with sprintf():
#include <stdio.h>
int main(void)
{
int i = 12345;
char buf[BUFSIZ];
char name[] = "Hammer";
printf ("i is: %d\n", i);
sprintf(buf, "%d", i);
printf ("buf is now: %s\n", buf);
sprintf(buf, "%s %010d", name, i);
printf ("buf has changed to : %s\n", buf);
return(0);
}