-1
#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.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
Mux
  • 11
  • 2

3 Answers3

1

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.

ajay
  • 9,402
  • 8
  • 44
  • 71
0

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
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
0

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.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198