How to Convert an Integer to a String in C

  1. sprintf() Function to Convert an Integer to a String in C
  2. itoa() Function to Convert an Integer to a String in C

This tutorial introduces how to convert an integer to a string value in C. There are different methods for conversion of an integer to a string in C, like sprintf(), itoa() function.

sprintf() Function to Convert an Integer to a String in C

As its name suggests, it is used to print any value into a string. This function gives an easy way to convert an integer to a string. It works the same as the printf() function, but it does not print a value directly on the console but returns a formatted string. The return value is usually discarded, but if an error occurs during the operation, it returns -1.

sprintf() Syntax:

int sprintf(char *str, const char *format, [arg1, arg2, ... ]);
  • str is a pointer to a char data type.
  • format is is used to display the type of output along with the placeholder.
  • arg1, arg2 are integers to convert into a string.

Example Code of sprintf() to Convert an Integer to a String in C

#include <stdio.h>

int main(void)
{
	int number;
	char text[20]; 

	printf("Enter a number: ");
	scanf("%d", &number);

	sprintf(text, "%d", number);   

	printf("\nYou have entered: %s", text);

	return 0;
}

Output:

Enter a number: 20
You have entered: 20

itoa() Function to Convert an Integer to a String in C

itoa() is a type casting function in C. This function converts an integer to a null-terminated string. It can also convert a negative number.

itoa() Syntax

char* itoa(int num, char * buffer, int base) 
  • num is an integer number.
  • buffer is a pointer to char data-type.
  • base is a conversion base. It defines an integer value to convert it to a base value and stores it into a buffer. If the base is 10 and the value is negative, the resulting string will precede with the minus’s (-) sign.

Example Code of itoa() Function to Convert an Integer to a String in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(void)
{
    int number,l;
    char string[20];
    
    printf("Enter a number: ");
    scanf("%d", &number);
    
    itoa(number,string,10);
    
    printf("String value = %s\n", string);
    
    return 0;
}

Output:

Enter a number: 15
String value: 15
Warning

itoa() is not a ANSI C standard function. It may not work on your GCC compiler depending on your platform.

Related Article - C Integer

  • How to Convert a String to Integer in C
  • Related Article - C String

  • How to Get a Substring in C