0

I am working on a C source code and to get input it does

 while(!feof(stdin)){
        fscanf(stdin, "%d ...

What I can't understand is how do you get it to stop taking input and process the input? Ctr+Z just kills the whole process and I tried pressing enter a bunch without input and it doesn't work.

Celeritas
  • 14,489
  • 36
  • 113
  • 194

1 Answers1

7

EOF (usually a define with value -1) indicator on Linux will match CTRL+D (ASCII code 4) for text files. It's generic enough to be used with both binary and text files and on different environments too (for example it'll match CTRL+Z for text files on DOS/Windows).

In your case loop will exit when user will type CTRL+D as input because input stream will reach its end (then feof() will return non zero).

To see drawbacks (not so obvious behavior) for this method just try yourself to input some text then printf it out (using various inputs, terminating at the beginning or in the middle of a line). See also this post for more details about that.

Better (least astonishment) implementation may avoid fscanf and rely on fgets return value (for example). Compare its behavior with this:

char buffer[80];
while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
    // ...
}
Community
  • 1
  • 1
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208