代码1:
char ch1, ch2;
printf("Input the first character:");
scanf("%c", &ch1);
while(getchar()!='\n');
printf("Input the second character:");
ch2 = getchar();
在这种情况下,
while(getchar()!='\n');
清除了第一个输入按下的回车键
效果。代码2:
char ch1, ch2;
printf("Input the first character:");
scanf("%c", &ch1);
while(getch()!='\n');
printf("Input the second character:");
ch2 = getchar();
在这种情况下,
while(getch()!='\n');
不会清除第一个输入的enter-key
的效果。因此循环无限执行。在这种情况下,
getch()
和getchar()
的功能有什么区别?
getchar()
将进入无限循环。你没有遇到这个问题是因为你没有终止标准输入(stdin)。不同的终端有不同的方法,有些使用Ctrl-D或Ctrl-Z,还有其他方式。EOF与Enter键是不同的。 - chux - Reinstate Monica