【发布时间】:2020-09-03 14:15:23
【问题描述】:
//first example
void readInWBW()
{
int ch;
while((ch=getchar()) != EOF)
putchar(ch);
}
当我输入“qweCTRL+D”时,第一次输入 ctrl+z 的地方只是刷新缓冲区,然后我重新输入 "ctrl+d" 所以它就像 "qweCTRL+DCTRL+D",然后 EOF 工作,程序终止。 结果是
$ ./a.out
qweqwe$
//second example
void guess()
{
int guess = 1;
printf("Pick an integer from 1 to 100. I will try to guess ");
printf("it.\nRespond with a y if my guess is right and with");
printf("\nan n if it is wrong.\n");
printf("Uh...is your number %d?\n", guess);
while (getchar() != 'y'){ //<---------------------------
printf("Well, then, is it %d?\n", ++guess); //<----------
sleep(1);
}
printf("I knew I could do it!\n");
}
在这个例子中,我输入“qweCTRL+D”,它会显示 3 次“Well, then...”,但是如果我再次输入 CTRL+D,程序将进入无限循环。 结果是:
Pick an integer from 1 to 100. I will try to guess it.
Respond with a y if my guess is right and with
an n if it is wrong.
Uh...is your number 1?
qweWell, then, is it 2? //<--------------------------
Well, then, is it 3?
Well, then, is it 4?
Well, then, is it 5?
Well, then, is it 6?
Well, then, is it 7?
Well, then, is it 8?
Well, then, is it 9?
Well, then, is it 10?
Well, then, is it 11?
^C
//third example
void test()
{
char ch;
while((ch = getchar()) != '#')
putchar(ch);
}
我尝试像其他示例一样输入“qweCTRL+D”,但是在刷新缓冲区后,“CTRL+D”不再响应,即使我输入“#”,它仍然没有终止。 结果是:
$ ./a.out
qweqwe
#
#
^C
$
我不明白为什么在 example2 和 example3 中有无限循环并且无法终止程序。谁能解释一下,谢谢。
【问题讨论】:
-
第二个和第三个例子不检查 EOF。