我是 C 编程和 Ubuntu 的新手。我正在阅读 D.M Ritchie 的《C 编程语言》,其中我发现了以下代码:
#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?
Quoting @Veritas 的评论,
在 Linux 上,Ctrl-D 仅在缓冲区已为空时才起作用,否则它只会刷新缓冲区。因此,除非他之后按下 Enter 键时没有任何字符,否则他必须按 Ctrl-D 两次。
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)