Ctrl-d did not stop while (getchar ()! = EOF) loop

Here is my code. I run it in ubuntu using terminal. when I type (a Ctrl D ) in the terminal, the program did not stop, but continued to wait for input.

Doesn't Ctrl D equal EOF in unix?

Thanks.

#include<stdio.h> main() { int d; while(d=getchar()!=EOF) { printf("\"getchar()!=EOF\" result is %d\n", d); printf("EOF:%d\n", EOF); } printf("\"getchar()!=EOF\" result is %d\n", d); } 
+7
source share
2 answers

EOF is not a symbol. EOF is the macro returned by getchar() when it reaches the end of the input or encounters an error. ^D not an EOF character. What happens on Linux when you press ^ D on a line is that it closes the stream, and the getchar() call reaches the end of the input and returns an EOF macro. If you type ^D somewhere in the middle of the line, the stream will not be closed, so getchar() returns the values ​​it reads, and your loop does not exit.

Learn more about stdio in the C faq section .

Additionally:

In modern systems, it does not reflect any actual end-of-file character stored in the file; this is a signal that no more characters are available.

+11
source

In addition to Jon Lin, answer about EOF, I'm not sure if the code you wrote is what you intended. If you want to see the value returned from getchar in variable d , you need to change the while statement to:

  while((d=getchar())!=EOF) { 

This is due to the fact that the inequality operator has a higher priority than assignment. So in your code, d will always be either 0 or 1 .

+6
source

All Articles