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.

0

1 Answer 1

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) {
    // ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Should it be upper case d? I tried with lower case and it works on this machine.
There is not an upper case/lower case CTRL+D. It's just ASCII code 4 (CTRL-D is a shortcut to produce that code).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.