简体   繁体   English

读取整数,直到C中的EOF

[英]Read integers until EOF in C

I need to read all integers until the EOF. 我需要读取所有整数,直到EOF。 I'm trying this code and the problem is that the program doesn't detect the EOF and keeps running. 我正在尝试此代码,问题是该程序未检测到EOF并保持运行。 What I need is to receive all the data and proceed to the next line of code automatically (the code works with pressing Ctrl-D after the input). 我需要的是接收所有数据并自动进入下一行代码(在输入后按Ctrl-D即可运行代码)。

int x, sum = 0;

while (scanf("%d", &x) == 1) {
    sum += x;
}

if (feof(stdin)) {
    printf ( "SUM: %d\n", sum );
} else {
    printf("ERROR\n");
}

return 0;

How do you want to specify EOF? 您要如何指定EOF?

  • ^D is the way to do it in the terminal in Unix. ^D是在Unix终端中执行此操作的方法。 In the Windows terminal, ^Z does the same thing. 在Windows终端中, ^Z执行相同的操作。 scanf will return -1 and feof() will be non zero. scanf将返回-1feof()将为非零。 But any further input from stdin will fail too. 但是任何来自stdin的输入也会失败。

  • Do you want to just hit the enter key? 您是否只想按Enter键? If so, you have to check for that after scanf , otherwise the next call to scanf will read the linefeed and ignore it. 如果是这样,你必须检查,经过scanf ,否则下次调用scanf将读取换行,并忽略它。

  • If you type something that is neither white space nor a number, scanf will return 0 and leave the unmatched character in the input stream. 如果键入的内容既不是空格也不是数字,则scanf将返回0 ,并将不匹配的字符保留在输入流中。 Your program will print ERROR . 您的程序将显示ERROR Is this what is happening? 这是怎么回事吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM