【问题标题】:While loop not waiting for input with scanf("%d")While 循环不等待 scanf("%d") 的输入
【发布时间】:2016-07-22 13:59:21
【问题描述】:

我有一个 while 循环,它打印一个整数提示。我想在用户输入一个字符时进行错误检查,比如'a'。但是,当我输入“a”时,它会永远打印“输入种子:种子必须是整数值,请重试”。

int getSeed() {
    int scanned, seed;

    while (scanned == 0) {
       printf("Enter the seed: ");
       scanned = scanf("%d", &seed);
       if (scanned == 0) {
          printf("Seed must be an integer, try again\n");
       }
    }
    return seed;
}

如何打印出来

Enter the seed: a Seed must be an integer, try again Enter the seed:

谢谢。

编辑:解决了,我添加了 getchar();在scanf之后。

【问题讨论】:

  • scanf not reading input的可能重复
  • 你的解决方案并不能真正解决它。如果有人进入,事情仍然会出错,例如“aa”。如果您想读取一行然后解析它,请编写代码来执行此操作。

标签: c while-loop


【解决方案1】:

scanf 检查您的输入字符并发现它与转换说明符不匹配,因此将其放回输入流中。
然后在您的代码中的while 循环中再次到达scanf,并且再次发生上述过程(因为您在输入流中编写的a 仍然存在)

因此,更好的解决方案是将其作为字符(或字符串)读取,然后将其转换为整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2015-07-30
    • 1970-01-01
    相关资源
    最近更新 更多