C中是/否循环

时间:2013-09-05 03:17:46

标签: c while-loop scanf

我只是不明白为什么这个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;
}

3 个答案:

答案 0 :(得分:10)

将第二个scanf更改为:

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

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

答案 1 :(得分:3)

解决了各种问题

#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;
}

答案 2 :(得分: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。除了提示之外,通常最好使用换行符结束打印操作(而不是在开始时使用换行符)。在读取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并且循环退出。