In C, integers can be represented as strings with each digit represented by corresponding numeric character. In this article, we will learn how to convert integers into the string
Examples
Input: 1234
Output: "1234"
Explanation: The integer 1234 is converted to the string "1234".Input: -567
Output: "-567"
Explanation: The integer -567 is converted to the string "-567".
There are various methods that can be used to convert integer to a string in C:
Manual Conversion Using Loop
We can convert an integer to a string manually by extracting each digit one by one and converting it to its corresponding character by using their ASCII code and storing it in the character array to form a string.
#include <stdio.h>
#include <string.h>
void intToStr(int N, char *str) {
int i = 0;
// Save the copy of the number for sign
int sign = N;
// If the number is negative, make it positive
if (N < 0)
N = -N;
// Extract digits from the number and add them to the
// string
while (N > 0) {
// Convert integer digit to character and store
// it in the str
str[i++] = N % 10 + '0';
N /= 10;
}
// If the number was negative, add a minus sign to the
// string
if (sign < 0) {
str[i++] = '-';
}
// Null-terminate the string
str[i] = '\0';
// Reverse the string to get the correct order
for (int j = 0, k = i - 1; j < k; j++, k--) {
char temp = str[j];
str[j] = str[k];
str[k] = temp;
}
}
int main() {
int N = 1234;
char str[12];
intToStr(N, str);
printf("String: %s\n", str);
return 0;
}
Output
String: 1234
Using sprintf() Function
We can also use the sprintf function in C to convert an integer to a string. The working of sprintf() function is similar is similar to printf() but instead of printing the output it stores the formatted output into a character array(string buffer).
#include <stdio.h>
int main() {
// Integer to be converted
int N = 86;
// Buffer to hold the resulting string
char str[20];
// Converting integer to string using sprintf
sprintf(str, "%d", N);
printf("The integer %d converted to string is: %s\n",
N, str);
return 0;
}
Output
The integer 86 converted to string is: 86
Note: We can also use the snprintf function which is similar to sprintf but with a buffer size limit, which helps prevent buffer overflows.
Using itoa() Function
itoa() is a non-standard function available in some C compilers like MSVC, etc. It stands for Integer TO ASCII. It converts the given integer value to a null-terminated string and stores the result in the character array( buffer) defined by string parameter.
#include <stdio.h>
#include <stdlib.h>
int main() {
int N = 1234;
// Declare a character array 'str' t store the converted
// string
char str[12];
// Calling itoa()
itoa(N, str, 10);
printf("String: %s\n", str);
return 0;
}
Output
String: 1234