ctrl-d didn't stop the while(getchar()!=EOF) loop [duplicate]

江枫思渺然 提交于 2019-11-26 08:26:26

问题


This question already has an answer here:

  • Canonical vs. non-canonical terminal input 1 answer

Here is my code. I run it in ubuntu with terminal. when I type (a CtrlD) in terminal, the program didn\'t stop but continued to wait for my input.

Isn\'t CtrlD equal to EOF in unix?

Thank you.

#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);
}

回答1:


EOF is not a character. The EOF is a macro that getchar() returns when it reaches the end of input or encounters some kind of error. The ^D is not "an EOF character". What's happening under linux when you hit ^D on a line by itself is that it closes the stream, and the getchar() call reaches the end of input and returns the EOF macro. If you type ^D somewhere in the middle of a line, the stream isn't closed, so getchar() returns values that it read and your loop doesn't exit.

See the stdio section of the C faq for a better description.

Additionally:

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




回答2:


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

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

This is because the inequality operator has higher precedence than assignment. So, in your code, d would always be either 0 or 1.



来源:https://stackoverflow.com/questions/11944314/ctrl-d-didnt-stop-the-whilegetchar-eof-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!