【发布时间】:2011-12-15 10:35:04
【问题描述】:
我有以下程序:
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 字符?
接下来,作者提出了2种解决此类问题的方法:
使用
fflush()-
这样写一个函数:
void clear (void) { while ( getchar() != '\n' ); }
这段代码确实有效。但我无法解释自己是如何工作的?因为在while语句中,我们使用getchar() != '\n',意思是读取除'\n'以外的任何单个字符?如果是这样,在输入缓冲区中仍然保留'\n' 字符?
【问题讨论】: