【发布时间】:2018-08-21 06:36:25
【问题描述】:
在问这个问题之前,我已经阅读:fgetc(stdin) in a loop is producing strange behaviour。我正在编写一个程序来询问用户是否要退出。这是我的代码:
#include<stdio.h>
#include<stdlib.h>
int ask_to_exit()
{
int choice;
while(choice!='y'||choice!='n')
{ printf("Do you want to continue?(y/n):");
while((fgetc(stdin)) != '\n');
choice = fgetc(stdin);
if(choice=='y') return 0;
else if(choice=='n') return 1;
else printf("Invalid choice!\n");
}
}
int main()
{
int exit = 0;
while(!exit)
{
exit = ask_to_exit();
}
return 0;
}
由于 fflush(stdin) 是未定义的行为,我没有使用它。在遵循另一个问题中的解决方案后,我仍然收到错误消息。下面是上述程序的试运行:
$./a.out
Do you want to continue?(y/n):y<pressed enter key>
<pressed enter key>
Invalid choice!
Do you want to continue?(y/n):y<pressed enter key>
<pressed enter key>
Invalid choice!
Do you want to continue?(y/n):n<pressed enter key>
<pressed enter key>
Invalid choice!
Do you want to continue?(y/n):n<pressed enter key>
n<pressed enter key>
<program exits>
【问题讨论】:
-
使用
choice变量而不初始化它! -
这有关系吗??我正在检查 while(choice!='y'||choice!='n') ,所以即使它没有初始化,它也不会是 'y' 或 'n',所以它应该可以工作,对吧?
-
do... while()循环更适合这种情况,而不是while循环。 -
是的,这很重要。使用未初始化的局部变量是未定义的行为
-
choice!='y'||choice!='n'总是为真。如果是一个,那不可能是另一个。如果两者都不是,仍然是正确的。如果是两者,请致电您的大学天体物理系,因为您发现了一个虫洞。