How to use scanf to input strings into an array in C language?
To input an array of strings in C language, the scanf function can be used. Here is a common way to input strings arrays using scanf:
#include <stdio.h>
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
printf("您输入的字符串是:%s\n", str);
return 0;
}
In the example above, we first define an array called ‘str’ of type char to store the input string. Next, we use the scanf function with the %s format specifier to read the string and store it in ‘str’. Finally, we use the printf function to output the input string to the console.
It’s important to note that the scanf function stops reading when it encounters a space or newline character, so it cannot input strings with spaces. Additionally, to ensure that the input string does not exceed the size of the array, it is best to use the %ns format character in the scanf function, where n is the size of the array. For example, scanf(“%99s”, str); can ensure that the input string does not exceed 99 characters.