【问题标题】:scanf resulting in infinite loop [duplicate]scanf导致无限循环[重复]
【发布时间】:2013-12-20 17:30:54
【问题描述】:

我之前遇到过这个问题,但使用其他运算符解决了这个问题。但是我认为不能在这里使用相同的运算符(getche();)。无论如何,这很好用,但是如果我输入一个字母,它就会进入无限循环。

printf("Enter the number of the passenger you wish to edit.");
scanf("%d", &userchoice);

do
{
    if(userchoice <= count || userchoice <= 1)
    {
        flag = 0;
    }
    else
    {
        printf("Please enter a valid input!");
        scanf("%d", &userchoice);
        flag = 1;
    }
} while (flag == 1);

【问题讨论】:

  • 你的count值是多少
  • 你的意思是 userchoice 必须在 1 和 count 之间?如果是,应该是if(userchoice &lt;= count &amp;&amp; userchoice &gt;= 1)
  • 你应该写下用户选择的类型是什么
  • 无限循环是什么意思?是否打印“请输入有效的输入!”无限次?

标签: c scanf infinite-loop


【解决方案1】:

你应该看到这个答案:

https://stackoverflow.com/a/1716066/2263879

问题出在你的 scanf 上。

【讨论】:

  • 哇,我不知道 scanf 没有清除输入缓冲区中的无效输入。你每天都能学到一些东西,谢谢。
  • 没错!你明白了!
【解决方案2】:

是的,它会进入。

由于您正在检查 userchoice

P.S:我假设 count 在这里是很小的数字,因为你没有提供它的值。

【讨论】:

  • 计数只是结构的数量。不,不是当前的问题,问题是你输入了一些不好的东西,比如一个字母它进入无限循环并输出 printf(请输入有效的输入!)直到它崩溃并忽略 scanf
【解决方案3】:

你的意思是用户在 1 和 count 之间的选择,那么第一个 if 是不正确的。 当您想在 1 和 count 之间进行测试时,此代码有效。

    #include <stdio.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
    signed int count = 5;

    signed int flag = 1;
    signed int userchoice = 0;

    printf("Enter the number of the passenger you wish to edit:");
    scanf("%d", &userchoice);

    do {
        if(userchoice <= count && userchoice >= 1) {
            flag = 0;
        } else {
            char c = '0';
            if (scanf("%d", &userchoice) == 0) {
                    printf("Please enter a valid input!\n");
              do {
                c = getchar();
              }
              while (!isdigit(c));
              ungetc(c, stdin);
            }
        }
    } while (flag == 1);

    printf("Done!");
}

输出:

a 无效,因为它不是数字,6 大于 count。 3 是可能的并被接受。

Enter the number of the passenger you wish to edit:a
Please enter a valid input!
6
3
Done!

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 2012-10-05
    • 2016-06-05
    • 2012-09-27
    • 2012-01-07
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多