【问题标题】:why does my int while loop keeps going when i scan for a number?为什么当我扫描一个数字时我的 int while 循环一直在进行?
【发布时间】:2014-04-25 11:29:59
【问题描述】:

我在使用 while 循环时遇到了问题。我必须输入一个大于 0 且小于 81 的数字。当我使用像 -1,0,1,2,82 这样的数字时,它会很好并且我得到预期的结果,但是当我使用字母时它会继续通过我的while循环。我在 Eclipse 中使用了调试器,当我在 while 循环中时,amount 由于 scanf 失败而自动设置为“0”。为什么我插入一个字母时一直循环?

#include <stdio.h>
#include <stdlib.h>

int main(){
    int amount = 0;
    printf("Give a number:\n");
    fflush(stdout);
    scanf("%d",&amount);
    while(amount <= 0 || amount >= 81){
        printf("Wrong input try again.\n");
        printf("Give a number:\n");
        fflush(stdout);
        scanf("%d",&amount);
    }
    return EXIT_SUCCESS;
}

【问题讨论】:

  • %d 不用于信件。在while 中验证之前,您需要将char 输入转换为int
  • 使用错误的格式说明符是未定义的行为。
  • @Dayalrai 我明白了,但目前它将数量设置为 0。这是一个整数。所以它应该对我有效。对吗?
  • 如果输入是一个字母,并且amount 设置为零,那么循环当然会继续,因为while 子句的计算结果为真:while (amount &lt;= 0 || 等于零。小提示:研究scanf 存在的问题,并尽可能检查函数的返回值
  • 您必须在使用扫描值之前检查scanf()返回值。它是 I/O,它可能会失败。不知道为什么这么多人在这方面失败了。

标签: c while-loop scanf


【解决方案1】:

您需要确保scanf() 工作正常。使用返回的值来做到这一点

if (scanf("%d", &amount) != 1) /* error */;

当它不起作用时(例如,因为在输入中发现了一个字母),您可能希望摆脱错误的原因。

获得用户意见的更好选择是使用fgets()

【讨论】:

    【解决方案2】:

    查看这个相关问题:scanf() is not waiting for user input

    原因是当您使用 char 按 Enter 时,scanf 失败并且没有吃掉输入提要中的 char。结果,下一个块开始包含您之前输入的任何内容。

    您可以通过在while 循环内的scanf() 之前添加getchar() 来检查。您会注意到,当您的行中有无效字符时,它会重复 while 循环多次,然后停止并等待输入。每次循环运行时,getchar() 都会吃掉输入中的一个无效字符。

    不过,最好不要这样使用scanf。看看这个资源: Reading a line using scanf() not good?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-07
      • 2021-04-09
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 2018-02-18
      • 2023-01-05
      • 1970-01-01
      相关资源
      最近更新 更多