How do you input a string in the C language?

In C language, you can use the scanf function to input a string.

#include <stdio.h>

int main() {
    char str[100];

    printf("请输入字符串:");
    scanf("%s", str);

    printf("您输入的字符串是:%s\n", str);

    return 0;
}

In the example above, we defined a character array called str with a length of 100 to store the inputted string. We then used the scanf function to read the string inputted by the user, specifying the %s format specifier to read the string. The inputted string is stored in the str array. Finally, we used the printf function to output the string read to the screen.

It should be noted that the scanf function will stop reading when it encounters spaces, tabs, or newline characters, so it can only read strings without spaces. If you need to read strings with spaces, you can use the fgets function.

#include <stdio.h>

int main() {
    char str[100];

    printf("请输入字符串:");
    fgets(str, sizeof(str), stdin);

    printf("您输入的字符串是:%s\n", str);

    return 0;
}

In the example above, we used the fgets function to read a string, which can read strings containing spaces. The first parameter of the fgets function is a pointer to a character array, the second parameter is the size of the character array, and the third parameter is the file pointer, typically represented by stdin for standard input. The read string will be stored in the character array str.

bannerAds