How to input strings consecutively in the C language?

In the C language, you can use the scanf function to input strings consecutively. Below is an example code:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    char str[MAX_SIZE];
    int i, n;
    
    printf("请输入要输入的字符串个数:");
    scanf("%d", &n);
    
    for (i = 0; i < n; i++) {
        printf("请输入字符串%d:", i + 1);
        scanf("%s", str);
        
        printf("你输入的字符串%d为:%s\n", i + 1, str);
    }
    
    return 0;
}

In the code above, the scanf function is first used to get the number of strings to input. Then a for loop is used to continuously input strings, and each string is output after it is entered. It is important to note that the scanf function uses spaces, tabs, or new lines as delimiters when reading strings, so if the input string contains a space, only the part before the space will be read.

Furthermore, to ensure that the input string does not exceed the predetermined maximum length, you can define a sufficiently large character array, such as the ‘str’ array in the code above, and use the ‘%s’ format specifier to read the string.

bannerAds