How can numbers be converted to strings in C language?
In C language, we can use the sprintf() function to convert numbers to strings. Here is a simple example:
#include <stdio.h>
int main() {
int num = 12345;
char str[10];
sprintf(str, "%d", num);
printf("Number as string: %s\n", str);
return 0;
}
In this example, we are converting the value of the integer variable ‘num’, which is 12345, into a string and storing it in a character array ‘str’. Afterwards, we are using the printf() function to print the converted string.
Additionally, if you want to convert a floating point number to a string, you can use the following method:
#include <stdio.h>
int main() {
double num = 123.456;
char str[20];
sprintf(str, "%f", num);
printf("Number as string: %s\n", str);
return 0;
}
In this example, we are converting the value of the floating point variable num from 123.456 to a string, storing it in a character array str. Then, we use the printf() function to print the converted string.