3
#include <stdio.h>
int main()
{
    char c = getchar(); //EOF (ctrl + d )
    while( ( c = getchar() ) != '?' )
    {
        printf( "%d\n", c == EOF );//infinite loop printing 1
    }
}

What happens here?

It is as if EOF completely blocks reading anything after it?

A M
  • 14,694
  • 5
  • 19
  • 44
mdjukan
  • 41
  • 3
  • 4
    That's the whole purpose of EOF, to signal the stream to stop reading. E.g. when all content from a file has been read (hence EOF = end of file) the stream should stop reading. – Lukas-T Dec 16 '21 at 06:55
  • 2
    EOF is short for "end of file". Did you know that? I assume you do. So please explain what you expect to read from a file after you arrived at the end of the file or what other special aspects put your situation apart. – Yunnosch Dec 16 '21 at 06:59
  • regarding: `char c = getchar();` the function: `getchar()` actually returns an `int`. and, depending on your implementation of `char` (signed or unsigned)` it might not be able to recognize EOF`. So, start by `int c = getchar();` – user3629249 Dec 17 '21 at 00:14

1 Answers1

7

You need to call clearerr on stdin to clear the EOF. Also, note that getchar returns an int and not a char because EOF does not fit in a char.

kaylum
  • 13,833
  • 2
  • 22
  • 31