我有以下程序:
int main(int argc, char *argv[])
{
char ch1, ch2;
printf("Input the first character:"); // Line 1
scanf("%c", &ch1);
printf("Input the second character:"); // Line 2
ch2 = getchar();
printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
system("PAUSE");
return 0;
}
正如上面代码的作者所解释的:该程序将无法正常运行,因为在第1行,当用户按下Enter键时,它将保留在输入缓冲区2中的字符:Enter key (ASCII code 13)
和\n (ASCII code 10)
。因此,在第2行,它将读取,\n
而不会等待用户输入字符。
好我知道了 但是我的第一个问题是:为什么第二个getchar()
(ch2 = getchar();
)不读取Enter key (13)
,而不是\n
字符?
接下来,作者提出了两种解决此类问题的方法:
使用
fflush()
编写这样的函数:
void clear (void) { while ( getchar() != '\n' ); }
该代码实际上起作用了。但是我无法向自己解释它是如何工作的?因为在while语句中,我们使用getchar() != '\n'
,这意味着读取除'\n'
?之外的任何单个字符。如果是这样,则在输入缓冲区中仍然保留'\n'
字符?