【问题标题】:do-while loop does not end [duplicate]do-while循环没有结束[重复]
【发布时间】:2018-04-06 18:47:26
【问题描述】:

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

您的回答不正确,它必须是 1 或 0

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

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;

}

【问题讨论】:

  • 提示:想一个数字choicechoice != 0choice != 1 的计算结果都是false;这是您需要输入的数字才能结束循环。
  • 是的,它会读入回车键。
  • 超级骗子。很多很多类似的Q:(

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


【解决方案1】:

or 替换为 and,因为您的 while 正在检查某个条件并在该条件为真时继续。

【讨论】:

    【解决方案2】:
    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,以使当前代码正常运行。

    【讨论】:

    • 这样做更符合逻辑scanf(" %d",&choice)
    • @ChrisTurner 是的,但它也适用于字符...取决于他最喜欢的方式。
    • choice 被定义为 int 而不是 char...
    • 没关系,scanf会将值放在整数值的低位字节上。
    • 这是一个潜在的错误(取决于 int 的不确定初始化值),也是未定义的行为。当它很容易修复时,您必须修复它。
    【解决方案3】:

    您的情况检查不正确:

    改一下

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 2016-08-24
      相关资源
      最近更新 更多