How can you convert between int and string in C language?
In C language, you can use the sprintf function to convert an int type to a string type, and use the atoi function to convert a string type to an int type.
Here is an example code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num = 123;
char str[10];
// 将int转化为string
sprintf(str, "%d", num);
printf("转化后的string为: %s\n", str);
// 将string转化为int
int convertedNum = atoi(str);
printf("转化后的int为: %d\n", convertedNum);
return 0;
}
The output will be:
转化后的string为: 123
转化后的int为: 123
In this example, we first use the sprintf function to convert the integer num into a string str, where %d represents outputting the integer in decimal form. We then use the atoi function to convert the string str back into an integer called convertedNum.