问题
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