C语言 你如何在 C 中读取 scanf 直到 EOF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3764014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:29:02  来源:igfitidea点击:

How do you read scanf until EOF in C?

cscanfeof

提问by JJRhythm

I have this but once it reaches the supposed EOF it just repeats the loop and scanf again.

我有这个,但是一旦它达到假定的 EOF,它就会再次重复循环和 scanf。

int main(void)
{
        char words[16];

        while(scanf("%15s", words) == 1)
           printf("%s\n", words);

        return 0;
}

回答by codaddict

Try:

尝试:

while(scanf("%15s", words) != EOF)

You need to compare scanfoutput with EOF

您需要将scanf输出与EOF

Since you are specifying a width of 15in the format string, you'll read at most 15 char. So the words char array should be of size 16( 15 +1for nullchar). So declare it as:

由于您15在格式字符串中指定宽度,因此您最多将读取 15 个字符。所以字字符数组应该是大小1615 +1对于null字符)。所以将其声明为:

char words[16];

回答by zwol

Scanf is pretty much always more trouble than it's worth. Here are two better ways to do what you're trying to do. This first one is a more-or-less direct translation of your code. It's longer, but you can look at it and see clearly what it does, unlike with scanf.

Scanf 几乎总是比它的价值更麻烦。这里有两种更好的方法来做你想做的事情。第一个或多或少是对代码的直接翻译。它更长,但您可以查看它并清楚地看到它的作用,这与 scanf 不同。

#include <stdio.h>
#include <ctype.h>
int main(void)
{
    char buf[1024], *p, *q;
    while (fgets(buf, 1024, stdin))
    {
        p = buf;
        while (*p)
        {
            while (*p && isspace(*p)) p++;
            q = p;
            while (*q && !isspace(*q)) q++;
            *q = '
#include <stdio.h>
#include <ctype.h>
int main(void)
{
    int ch, lastch = '
if (scanf("%15s", word) == 1)
    printf("%s\n", word);
'; while ((ch = getchar()) != EOF) { if (!isspace(ch)) putchar(ch); if (!isspace(lastch)) putchar('\n'); lastch = ch; } if (lastch != '
while (scanf("%15s", word) == 1)
    printf("%s\n", word);
' && !isspace(lastch)) putchar('\n'); return 0; }
'; if (p != q) puts(p); p = q; } } return 0; }

And here's another version. It's a little harder to see what this does by inspection, but it does not break if a line is longer than 1024 characters, so it's the code I would use in production. (Well, reallywhat I would use in production is tr -s '[:space:]' '\n', but this is how you implement something like that.)

这是另一个版本。通过检查看它做了什么有点困难,但是如果一行的长度超过 1024 个字符,它不会中断,所以这是我将在生产中使用的代码。(嗯,实际上我会在生产中使用的是tr -s '[:space:]' '\n',但这就是您实现类似内容的方式。)

char word[16];

回答by Chris Dodd

Your code loops until it reads a single word, then exits. So if you give it multiple words it will read the first and exit, while if you give it an empty input, it will loop forever. In any case, it will only print random garbage from uninitialized memory. This is apparently not what you want, but what do you want? If you just want to read and print the first word (if it exists), use if:

您的代码循环直到读取一个单词,然后退出。因此,如果您给它多个单词,它将读取第一个并退出,而如果您给它一个空输入,它将永远循环。无论如何,它只会从未初始化的内存中打印随机垃圾。这显然不是你想要的,但你想要什么?如果您只想读取和打印第一个单词(如果存在),请使用 if:

int main()
{
    char str[100];
    scanf("[^EOF]",str);
    printf("%s",str);
    return 0;     
}

If you want to loop as long as you can read a word, use while:

如果你想循环只要你能读一个单词,使用while:

while ( gets(str) != NULL )

Also, as others have noted, you need to give the word array a size that is big enough for your scanf:

此外,正如其他人所指出的,您需要为单词数组提供足够大的大小以供您的 scanf 使用:

##代码##

Others have suggested testing for EOF instead of checking how many items scanf matched. That's fine for this case, where scanf can't fail to match unless there's an EOF, but is not so good in other cases (such as trying to read integers), where scanf might match nothing without reaching EOF (if the input isn't a number) and return 0.

其他人建议测试 EOF 而不是检查 scanf 匹配的项目数。对于这种情况,这很好,除非有 EOF,否则 scanf 不会无法匹配,但在其他情况下(例如尝试读取整数)则不太好,其中 scanf 可能不匹配任何内容而未达到 EOF(如果输入不是t 一个数字)并返回 0。

edit

编辑

Looks like you changed your question to match my code which works fine when I run it -- loops reading words until EOF is reached and then exits. So something else is going on with your code, perhaps related to how you are feeding it input as suggested by David

看起来你改变了你的问题以匹配我运行它时工作正常的代码 - 循环读取单词直到达到 EOF 然后退出。所以你的代码正在发生其他事情,可能与你如何按照大卫的建议提供输入有关

回答by Lucas Boeira

Man, if you are using Windows, EOF is not reached by pressing enter, but by pressing Crtl+Z at the console. This will print "^Z", an indicator of EOF. The behavior of functions when reading this (the EOF or Crtl+Z):

伙计,如果您使用的是 Windows,则无法通过按 Enter 到达 EOF,而是通过在控制台上按 Crtl+Z。这将打印“^Z”,EOF 的指示符。读取此内容时函数的行为(EOF 或 Crtl+Z):

Function: Output: scanf(...) EOF gets(<variable>) NULL feof(stdin) 1 getchar() EOF

Function: Output: scanf(...) EOF gets(<variable>) NULL feof(stdin) 1 getchar() EOF

回答by Codercool

I guess best way to do this is ...

我想最好的方法是......

##代码##

回答by Brian Campbell

You need to check the return value against EOF, not against 1.

您需要根据 而EOF不是针对来检查返回值1

Note that in your example, you also used two different variable names, wordsand word, only declared words, and didn't declare its length, which should be 16 to fit the 15 characters read in plus a NULcharacter.

请注意,在您的示例中,您还使用了两个不同的变量名称wordsword,仅声明了words,并没有声明其长度,它应该是 16 以适应读入的 15 个字符加上一个NUL字符。

回答by Psycho

For C users, this will also work

对于 C 用户,这也适用

##代码##