C中是/否循环

我只是不明白为什么这个Yes / No循环不起作用。 有什么建议? 鉴于输入是“Y”。 我只是想让它运行循环,然后再次询问Y或N. 如果是Y,则打印成功,如果是N,则打印出良好的再见声明。 什么原因?

int main(){ char answer; printf("\nWould you like to play? Enter Y or N: \n", answer); scanf("%c", &answer); printf("\n answer is %c"); while (answer == 'Y'){ printf("Success!"); printf("\nDo you want to play again? Y or N: \n"); scanf("%c", &answer); } printf("GoodBye!"); return 0; } 

修复了各种问题

 #include  int main(){ char answer; printf("\nWould you like to play? Enter Y or N: \n"); scanf(" %c", &answer); printf("\n answer is %c\n", answer); while (answer == 'Y'){ printf("Success!"); printf("\nDo you want to play again? Y or N: \n"); scanf(" %c", &answer); printf("\n answer is %c\n", answer); } printf("GoodBye!"); return 0; } 

将第二个scanf更改为:

 scanf(" %c", &answer); // ^ 

问题是,当你输入Y并按ENTER键时,新行仍然在输入缓冲区中,在%c消耗它之前添加一个空格。

您可以稍微减少代码中的重复次数,并通过编写以下内容来检查scanf()的结果(如您scanf()

 int main(void) { char answer; printf("Would you like to play? Enter Y or N: "); while (scanf(" %c", &answer) == 1 && answer == 'Y') { printf("Answer is %c\n", answer); printf("Success!\n"); printf("Do you want to play again? Y or N: "); } printf("GoodBye!\n"); return 0; } 

第一个printf()丢失了未使用的参数answer ; 第二个printf()收集了必要的第二个参数, answer 。 除了提示之外,通常最好使用换行符结束打印操作(而不是在开始时使用换行符)。 在读取stdin的输入之前,通常会通过C库刷新提示,因此您不需要在最后添加换行符。

由于printf()返回它打印的字符数,你也可以在条件中使用它:

 int main(void) { char answer; printf("Would you like to play? Enter Y or N: "); while (scanf(" %c", &answer) == 1 && printf("Answer is %c\n", answer) > 0 && answer == 'Y') { printf("Success!\n"); printf("Do you want to play again? Y or N: "); } printf("GoodBye!\n"); return 0; } 

这总是与答案相呼应,即使答案不是Y并且循环退出。