How to Convert an Integer to a String in C


If you need to convert an Integer to a String in C, then you can do one of the following:

Option 1 – Use sprintf()

int sprintf(char *str, const char *format, [arg1, arg2, ... ]);

You can do something like this:

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

Option 2 – Use itoa()

char* itoa(int num, char * buffer, int base)

You can do something like this:

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