【问题标题】:A simple while loop to check input stuck in infinite loop一个简单的while循环来检查输入卡在无限循环中
【发布时间】:2018-03-11 21:21:55
【问题描述】:

我很确定之前有人问过这个问题,但我找不到任何答案,所以我开始了。这是一行简单的代码,我无法让它退出while loop。如果我将|| 更改为&&,无论我按什么,循环都会退出。谢谢你的回答。

#include <stdio.h>   
int main()
{
    int answer;

    printf("Are you sure you want to exit the program? Type in 1 for yes and 2 for no.\n");
    scanf("%d", answer);

    //This is to check that the user inputs the right number if not error message is displayed
    while(answer <1 || answer > 2)
    {
        printf("Please type in 1 to exit the program and yes and 0 to keep playing. \n");
        scanf("%d", answer);
        flushall();
    }
    return 0;
}

【问题讨论】:

  • 减少你的问题。此外,如果没有 MCVE(请参阅网站指南),您的问题将是题外话。
  • 请记住,您需要将&amp;answer 而不是answer 作为参数传递给scanf。 :-)

标签: c while-loop scanf


【解决方案1】:

如果你想在 1 上退出,那么你只需要检查输入是否等于它,这就是为什么我想在它不等于 1 时扫描更多答案。如果是那么它将省略 while循环,直接去返回0。

我还改变了 scanf 的使用方式——当你声明一个变量时(在你的情况下回答),系统给它一个内存中的地址。然后你使用scanf从用户那里获取一个输入,在你获取输入之后,你把它写在那个变量的地址上,这样当你以后引用它的时候,系统就会去那个地址取值。

int main()
{
    int answer;

    printf("Are you sure you want to exit the program? Type in 1 for yes and 2 for no.\n");
    scanf("%d", &answer);

    //This is to check that the user inputs the right number if not error message is displayed
    while(answer != 1)
    {
        printf("Please type in 1 to exit the program and yes and 0 to keep playing. \n");
        scanf("%d", &answer);
    }
    return 0;
}

【讨论】:

    【解决方案2】:

    这是误解/忘记scanf 工作原理的常见案例之一。

    int scanf ( const char * format, ... );
    

    stdin.读取格式化数据

    它从stdin读取数据,并通过附加参数将数据按照参数格式存储到pointed位置。

    附加参数should point 已分配的对象的类型由格式字符串中的相应格式说明符指定。

    这意味着参数应该是pointers

    在你的情况下:

       int answer;
       scanf("%d", answer);
    

    answer 不是指针,而是int 类型的变量(对象)。

    要满足scanf,您必须使用指向answer 的指针。

    您可以使用unarymonadic operator & 来执行此操作,它给出了变量的地址。

       scanf("%d", &answer);
    

    或者你可以使用指向answer的指针:

       int answer;
       int answer_ptr = & answer; 
       scanf("%d", answer_ptr);
    

    这也是正确的,但通常不需要进行这种构造。

    第二行:

     while(answer <1 || answer > 2)
    

    您可能需要将其修改为

     while (answer != 1 && answer != 2) 
    

    如果您有兴趣在answer 等于12 时打破while loop

    【讨论】:

      猜你喜欢
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 2014-03-29
      • 2015-06-25
      • 2012-12-24
      相关资源
      最近更新 更多