如果用户输入超出所有可用选项,如何正确循环程序



我正在尝试运行一个C程序,如果简化,它看起来很像这样。但是,如果用户输入不是"y"one_answers"n",我得到的输出将为else语句运行两次所需的输出。我该如何解决这个问题?

#include <stdio.h>
#include <stdlib.h>
int main(){
char input;
printf("enter input: ");
scanf("%c", &input);
if (input == 'y'){
printf("yes");
}
else if (input == 'n'){
printf("no");
}
else{
printf("redo option!n");
main();
}
exit(0);
return 0;
}

接收到的每个错误输入字符的输出都是这样的

redo option!
enter input: redo option!
enter input:

您需要在scanf%c之前添加一个空格,如下所示:scanf(" %c", &input);。空格将使scanf跳过输入的换行符。

如果没有这个空间,换行符将从输入流中读取,并将被视为下一个字符输入,执行将进入else块。

您可能想要这个:

#include <stdio.h>
#include <stdlib.h>
int main() {
char input;
do
{
printf("enter input: ");
scanf(" %c", &input);    // note the space before %c
if (input == 'y') {
printf("yesn");
}
else if (input == 'n') {
printf("non");
}
else {
printf("redo option!n");
}
} while (1);               // loop forever
}
  • 使用一个简单的无限循环,而不是递归调用main
  • CCD_ 6中的%c之前的空格防止将其自身结束的行读取为字符

最新更新