How can strings be read character by character in the C language?

In the C language, you can use the scanf function to read strings one by one. Here’s an example code:

#include <stdio.h>

int main() {
    char str[100];

    printf("请输入字符串:\n");

    while (scanf("%s", str) != EOF) {
        printf("读取的字符串是:%s\n", str);
    }

    return 0;
}

In this code, we’re using an array of type char called str to store the read string with a size of 100, which can be adjusted based on the actual requirements.

The %s format specifier in the scanf function is used to read a string, skipping spaces, tabs, and newline characters in the string, and storing the string in a specified array. The scanf function returns the number of strings successfully read, returning EOF if reading fails or reaches the end of the file.

In the sample code, we use a while loop to continuously read strings until the scanf function returns EOF, ending the loop.

Please note that the scanf function stops reading when it encounters a space, tab, or newline, so it cannot read strings that contain spaces. If you need to read strings with spaces, you can use the fgets function or create a custom reading function to achieve this.

bannerAds