How to read a string in the C language?
In C language, you can use the scanf function to read in a string. Here is a simple example:
#include <stdio.h>
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
printf("你输入的字符串是:%s\n", str);
return 0;
}
In this example, we first define a character array called ‘str’ to store the input string. Then, we use the scanf function to read the string, with ‘%s’ as the format string indicating to read in a string. Finally, we use the printf function to output the input string.
It should be noted that the scanf function stops reading when it encounters a space, tab, or newline character. Therefore, if you need to read strings that include spaces, you can use the fgets function instead of the scanf function. An example is shown below:
#include <stdio.h>
int main() {
char str[100];
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
printf("你输入的字符串是:%s\n", str);
return 0;
}
In this example, the fgets function is used to read a string, where sizeof(str) represents the size of the str array, and stdin indicates reading data from standard input.