Hi,

I'm trying to parse whitespace-delimited doubles out of an input stream. I'm having trouble properly detecting the end of the file. Here is a small program which reproduces this:

Code:
#include <stdio.h>

int main(int argc, char *argv[]) {
    double d;
    double sum;
    int n;

    sum = 0;
    do {
        n = scanf(" %lf", &d);
        if (n == 1) sum += d;
    } while (n != EOF);

    if (!feof(stdin))
        perror(argv[0]);

    printf("%lf\n", sum);
    return 0;
}
This program has trouble detecting the end of the file when there is a trailing space after the last number. If I am entering numbers in from the terminal, I have to press ctrl-d to send EOF twice. I have another program that shells out to this one (not shown), and even after closing the stream on the parent process's end, the scanf() above seems to block forever after reading the last number out of the input. Interestingly, the program has no trouble with trailing whitespace if the input is redirected or piped in from the shell.

So, this fails (or requires two ctrl-d's)
$ ./test
1 2 3SPACE

But this does not:
$ echo "1 2 3 " | ./test

Nor does this:
$ echo "1 2 3 " > numbers
$ ./test < numbers

I think if can fix it for the first case, the problem when calling the program from another program and sending the input over a pipe will resolve itself.

How can I better detect EOF?

I'm on an ubuntu 10.10 machine, gcc 4.4.5

Thanks,
Jason