Why do I need to press CTRL+D twice to break out of `while ((c=getchar())!=EOF)` in Ubuntu 14.10?

独自空忆成欢 提交于 2019-12-19 10:21:54

问题


I am new to C Programming and Ubuntu. I was reading the "The C Programming Language" by D.M Ritchie where I found the following code:

#include <stdio.h>

int main()
{
    int c;
    int nc=0;
    while((c = getchar()) != EOF)
    {
        nc++;
    }

    printf("%d Characters \n",nc);

    return 0;
}

But while running the program I enter "Hello" ,then CTRL+D twice to get the actual number of characters which is 5.

But when I enter "Hello" then CTRL+D once, nothing happens, the terminal still waits for input.

Why?


回答1:


Quoting @Veritas's comment,

On linux Ctrl-D only works when the buffer is already empty otherwise it just flushes it. Therefore unless he has pressed enter without any characters after that, he will have to press Ctrl-D twice.

This explains the issue. You have to press it twice because you , after typing Hello, did not press the Enter to flush the input into the stdin. So the first time you press CTRL+D, it flushes the data into the stdin. The second time you press it, EOF is sent.



来源:https://stackoverflow.com/questions/30137434/why-do-i-need-to-press-ctrld-twice-to-break-out-of-while-c-getchar-eof

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