首页 > 解决方案 > 如何从 C 中的标准输入读取多行字符串?

问题描述

我是 C 编程的新手。假设我想从标准输入读取多行字符串。我怎样才能继续阅读直到仅包含 EOL 的行?

输入示例

1+2\n
1+2+3\n
1+2+3+4\n
\n (stop at this line)

似乎当我直接按 enter(EOL) 时,scanf将不会执行,直到输入 EOL 以外的其他内容。我该如何解决这个问题?

如果有人可以帮助我,我将不胜感激。谢谢你。

标签: cscanfstdin

解决方案


If you want to learn C, you should avoid scanf. The only use cases where scanf actually makes sense are in problems for which C is the wrong language. Time spent learning the foibles of scanf is not well spent, and it doesn't really teach you much about C. For something like this, just read one character at a time and stop when you see two consecutive newlines. Something like:

#include <stdio.h>

int
main(void)
{
        char buf[1024];
        int c;

        char *s = buf;

        while( (c = fgetc(stdin)) != EOF && s < buf + sizeof buf - 1 ){
                if( c == '\n' && s > buf && s[-1] == '\n' ){
                        ungetc(c, stdin);
                        break;
                }
                *s++ = c;
        }
        *s = '\0';
        printf("string entered: %s", buf);
        return 0;
}

推荐阅读