How to read strings in the C programming language?

In C language, you can use the scanf function to read strings.

#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 named str with a length of 100 to store the input string. We then used the scanf function to read the string, specifying the position to read the string with %s as the formatting string. It is important to note that %s can only read strings without spaces, so if the input string contains spaces, only the part before the space will be read.

Additionally, if you need to read a string that contains 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;
}

The fgets function can read a line of text, including the newline character. You need to specify the maximum length of the string to be read, and pass the input stream (stdin) as a parameter to the fgets function.

bannerAds