2

我只是不明白为什么这个是/否循环不起作用。有什么建议么?给定输入是“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;
}
4

3 回答 3

14

将第二个更改scanf为:

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

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

于 2013-09-05T03:27:17.557 回答
4

修复了各种问题

#include <stdio.h> 
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;
}
于 2013-09-05T03:34:26.103 回答
2

您可以稍微减少代码中的重复,并通过以下方式检查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。除提示外,通常最好用换行符结束打印操作(而不是在开始时使用换行符)。提示通常会在读取输入之前由 C 库刷新stdin,因此您不需要在这些末尾添加换行符。

由于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并且循环退出。

于 2013-09-05T03:50:14.453 回答