Getchar ()! = EOF

I run the following program from a book in the C programming language:

#include <stdio.h> main() { int c; while((c=getchar()) != EOF) putchar(); } 

When I run this program, I get inexplicable behavior. If I enter characters from the command line in the following sequence: {'h', 'e', 'l', 'l', 'o', '\n', '^D'} , then I get the following answer, printed on the screen: hello , after entering \n , and the program exits after entering ^D

However, when I change the sequence as follows: {'h', 'e', 'l', 'l', 'o', '^D'} , I get the following answer printed on the screen: hello , but the program does not finishes work. Shouldn't he leave as soon as I enter ^D ? I have to type ^D second time to exit the program. OR the program exits only after I entered ^D after \n . I do not understand why the program does not quit when I enter ^D Any thoughts?

I am running on a UNIX system.

+5
source share
1 answer

When you type ^ D ("end of transmission"), the input buffer is cleared and everything you have typed so far is sent to your program (without actually sending the character D). This is similar to entering a newline, but in this case the newline itself is also sent. A program considers its input closed when it reads null characters. This happens when you print a newline, then follow ^ D or two consecutive ^ D.

+17
source

Source: https://habr.com/ru/post/1207869/


All Articles