【问题标题】:C - scanf variable while it is not an integerC - scanf 变量,但它不是整数
【发布时间】:2020-06-28 01:42:01
【问题描述】:

我希望我的函数在我的变量不是整数时读取它。我的老师教我们使用var=scanf("%d", &x) 的形式,如果它是一个字符串,它将等于零。但是,当我输入一个字符串时,while 循环会重复而不要求我重新输入一个值。

这是我的算法:

int returnValue(int a, int b)
{
    int x, r;
    do{
        printf("Enter a value between %d and %d.\n", a, b);
        r=scanf("%d", &x);
    }while(x<a || x > b || r==0);
    return x;
}

如果有人对这个问题有任何想法,那就太好了。

【问题讨论】:

  • 您的实际问题是“如何读取一行输入并解析它以查看它是否包含整数?”

标签: c loops while-loop integer scanf


【解决方案1】:

while 循环重复而不要求我重新输入值。

未转换为int 的非数字输入仍保留在stdin 中以供下一次I/O 操作使用。 OP 代码中的每个循环都会再次读取相同的违规输入。 代码应该读取并丢弃非数字输入。

我建议不要使用scanf(),直到你知道它为什么不好。
同时,使用fgets() 读取用户输入的

int returnValue(int a, int b) {
  char buf[40];  // Suggest a size twice the expected max.
  int x, r;
  do {
    printf("Enter a value between %d and %d [inclusive].\n", a, b);
    if (fgets(buf, sizeof buf. stdin) == NULL) {
      fprintf(stderr, "End-of-file or input error\n");
      return INT_MIN;  // Or some other invalid value.    
    }
    int r = sscanf(buf, "%d", &x);  // or look into strtol() as a more robust solution
  } while(r != 1 || x < a || x > b); // test r first else x is undefined.
  return x;
}

【讨论】:

  • @DavidC.Rankin 在此处的示例代码中,INT_MIN。更强大的方法可以使用 int returnValue(int *dest, int a, int b) 将结果保存在 *dest 并返回 1 表示成功或 EOF 在文件末尾。
  • 是的,我在发表评论后就看到了编辑(并且认为您也必须读心......)
  • @DavidC.Rankin 我的同胞,我们都带来了不同的礼物。
猜你喜欢
  • 2013-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多