How to input a string in the C language?
In the C programming language, you can use the scanf function to input strings. Here are some commonly used methods:
- Utilizing the %s format specifier:
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
This method will read a string from standard input and store it in the str array. Input will stop when encountering a space or newline character.
- Use the %[^\n] format specifier:
char str[100];
printf("请输入一个字符串:");
scanf(" %[^\n]", str);
This method will read all characters except for line breaks and store them in an array called str.
- Use the fgets function:
char str[100];
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
This method will read a line of string from the standard input and store it in the str array.
It is important to note that all of the above methods will automatically add a null character ‘\0’ at the end of the string to indicate the end of the string.