do-while循环不会结束

时间:2017-10-25 15:31:26

标签: c if-statement scanf user-input do-while

我正在尝试做一个do-while循环,用户输入一个值,1或0,如果它不是1或0,那么循环将要求他们再次执行,直到他们输入1或0但是,在运行时,当我输入1或0时,它将继续在if语句中打印内容

  

您的回复不正确,必须为1或0

即使我已进入1/0,也永远留在这个循环中。它是否存储输入键?我缺少什么,我该如何解决这个问题?

int validateresultmanual(char* word, char* suggestion)
{
    int choice;
    int result;

    if(suggestion == NULL)
    {
        result = FALSE;
    }
    else
    {
        do
        {
            printf("Enter 0 for yes or 1 for no: Do you want to change %s to %s?\n", word, suggestion);
            scanf("%c", &choice);
            if(choice != 0 || choice != 1)
            {
                printf("You have given an incorrect response, it must either be 1 or 0\n");
            }
            else if(choice == 0)
            {
                printf ("\n yaaaaaaaaaaaaa \n");
                result = TRUE;
            }
            else if (choice == 1)
            {
                result = FALSE;
            }
     } while (choice != 0 || choice !=1 );
}
return result;

}

3 个答案:

答案 0 :(得分:4)

您的情况检查不正确:

更改此

if(choice != 0 || choice != 1)

if(choice != 0 && choice != 1)

答案 1 :(得分:0)

替换为,因为正在检查条件并在条件为真时继续。

答案 2 :(得分:0)

scanf("%c", &choice);

在此您将choice的值扫描为char,您应该减去'0'

choice -= '0';

扫描后。

同样,(choice != 0 || choice !=1 )始终为真,您应该在if语句和while语句中插入(choice != 0 && choice !=1 )

编辑:

如果choice的初始值不为0(可能会发生,因为您使用存储类说明符auto明确声明它),代码的行为是未定义的,如@anatolyg在这里评论

因此,您应该在循环之前使用scanf("%d", &choice);或初始化choice=0,以使当前代码合理。