Skip to content

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 ; }
Code language: C++ (cpp)

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 ; }
Code language: C++ (cpp)

See also  Count the Days in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x