C while循环程序

时间:2014-02-28 17:48:24

标签: c loops while-loop scanf break

C新手 简单地说,我只是不明白为什么这不起作用。 我想要它只是继续问你是否要玩,直到你输入'n'。 我一直在(error C2143: syntax error : missing ';' before 'break'

#include <stdio.h>
int main(void)
{
    char answer;
    printf("Would you like to play? Enter Y or N: ");
    while (scanf_s(" %c", &answer))
    {
        if (answer == 'y')
            printf("Answer is %c\n", answer);
        printf("Success!\n");
        printf("Do you want to play again? Y or N: ");
        else (answer == 'n')
        break;
    }
    printf("Goodbye\n");
    return 0;
}

6 个答案:

答案 0 :(得分:2)

ifelse必须紧挨着......你需要在那里有大括号:

    if (answer == 'y') 
    {
        printf("Answer is %c\n", answer);
        printf("Success!\n");
        printf("Do you want to play again? Y or N: ");
    }
    else
        break;

在if块中执行多个语句。

如果您想检查多个条件,请不要使用if / else,而是if / else if,例如:

    if (answer == 'y') 
    {
        printf("Answer is %c\n", answer);
        printf("Success!\n");
        printf("Do you want to play again? Y or N: ");
    }
    else if(answer == 'n')
        break;

答案 1 :(得分:0)

您需要使用括号重写if-else

if (answer == 'y') {
   printf("Answer is %c\n", answer);
   printf("Success!\n");
   printf("Do you want to play again? Y or N: ");
} else if (answer == 'n') {
   break;
}

答案 2 :(得分:0)

你不能写一个有条件的else 如果else没有执行,则执行if,而不进行第二次条件检查 如果你想要执行某些事情 如果if未执行且转义为真,请使用else if

答案 3 :(得分:0)

你必须写

else if (answer == 'n')

答案 4 :(得分:0)

除了@ Mike的答案添加所需的{}以将代码括在if的代码范围内,您还需要将else更改为elseif。< / p>

所以代码应该是这样的:

if (answer == 'y') 
{
    printf("Answer is %c\n", answer);
    printf("Success!\n");
    printf("Do you want to play again? Y or N: ");
}
else if (answer == 'n')
    break;

PS:根据向用户显示的指南消息("Would you like to play? Enter Y or N: ")的一个小建议,您可能还需要处理大写输入,即'Y'和{{ 1}}。你可以这样做:

'N'

答案 5 :(得分:0)

没有必要复制glibc rpmatch()函数,这可以很好地解释是/否答案。

#include <stdio.h>
#include <string.h>
#include <stdlib.h> 
int main(int argc, char **arg)
{
        int r;
        char *answer = NULL;
        size_t len = 0;
        while (1) {
                printf("Would you like to play? Enter Y or N: ");
                getline(&answer, &len, stdin);
                r = rpmatch(answer);
                if (r < 0)
                        printf("????\n");
                else if (r == 0)
                        break;
        }
        free(answer);
        return(0);
}