0
votes

I need to read all integers until the EOF. I'm trying this code and the problem is that the program doesn't detect the EOF and keeps running. 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).

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;
1
So what's the problem? - PSkocik
You've done everything correctly and it behaves as it should behave. ^D sends the EOF when your stdin is a terminal, and it works with real files too. - PSkocik
Perhaps there's confusion about what EOF means for STDIN? It doesn't mean "blank line". - Schwern

1 Answers

0
votes

How do you want to specify EOF?

  • ^D is the way to do it in the terminal in Unix. In the Windows terminal, ^Z does the same thing. scanf will return -1 and feof() will be non zero. But any further input from stdin will fail too.

  • Do you want to just hit the enter key? If so, you have to check for that after scanf, otherwise the next call to scanf will read the linefeed and ignore it.

  • 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. Your program will print ERROR. Is this what is happening?