EOF not working in while loop for getchar() in Ubuntu 11.10

1k Views Asked by At
#include <stdio.h>
#ifndef EOF
#define EOF (-1)
#endif

int main(void)
{
    int nb, nl, nt, c;
    nb = 0;
    nl = 0;
    nt = 0;
    while ((c = getchar()) != EOF){
        if (c == ' ')
            ++nb;
        else if (c == '\n')
            ++nl;
        else if (c == '\t')
            ++nt;
    }
    printf("Input has %d blanks, %d tabs, and %d newlines\n", nb, nt, nl);
    return 0;
}

Why is this code not working?

I compiled this code on my Ubuntu 11.10. If I replace EOF with \n, it's working as expected, but not with EOF.

3

There are 3 best solutions below

0
Ferenc Deak On

What do you mean by "it's not working"?

Firstly do not re-define EOF...

Secondly, press Ctrl+D to exit your application. It works for me:

d@reference:~/tmp$ ./a.out 
a
s
f <Ctrl+D>
Input has 0 blanks, 0 tabs, and 3 newlines
0
Olaf Dietsche On

The code works fine as it is.

To get an EOF on terminal input, you must press Ctrl-D at the beginning of a line, e.g.

$ ./program
Hello, world!
Ctrl-D

Now the program receives EOF and terminates the while loop.

0
ajay On

EOF is a macro defined in the stdio.h header file. It's an abbreviation for End-of-file and marks a condition where no more data can be read from an input stream. You should not redefine the macro. It is a value such that for any character ch, the expression ch == EOF always evaluates to false. On a *nix system, you enter this value by pressing Ctrl + D keys. On Windows systems, Ctrl+Z produces EOF.