FAQ > Convert an int to a string (char array) (C)


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 1) > Convert an int to a string (char array) (C)

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


/*
 * Program Output:
  i is: 12345
  buf is now: 12345
  buf has changed to : Hammer 0000012345
 *
 */

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


/*
 * Program Output:
  i is: 12345
  buf is now: 12345
  buf has changed to : Hammer 0000012345
 *
 */

Script provided by SmartCGIs