【问题标题】:Scanf to check reading of integer doesn't workScanf 检查整数的读数不起作用
【发布时间】:2015-01-04 23:32:50
【问题描述】:

我正在测试 scanf 函数以检查它是否根据用户输入读取了一个值(整数)。在我的 netbeans IDE 中,程序可以编译,但是在输入 x 值(如 '6')后,什么也没有发生,直到再次输入,然后程序继续正确反应,打印第一个 if 语句。对此问题的任何帮助将不胜感激:

这里又是一个sn-p:

int main(void)
{
    int x;
    printf("please enter a value for x");
    scanf("%d",&x);

    if(scanf("%d",&x) == 1) // checks to see if it contains one value
        printf("x value has one value");

    else
        printf("X value is not an integer or has more than one value");

}

【问题讨论】:

    标签: c input int scanf


    【解决方案1】:

    那是因为您的代码中有两个scanfs(一个在if 之前,另一个在if(...) 之前)。当您输入6 时,第一个scanf 占用它,然后if(...) 内的第二个scanf 等待下一个输入,使您输入两次。

    删除第一个scanf,你的程序就可以正常运行了!

    【讨论】:

    • 干杯伙伴,欣赏!
    【解决方案2】:

    嗯...第一个 scanf() 停止并等待您输入“6”,然后按 Enter。然后你让它执行另一个 scanf() 将重复该行为。

    完全放弃第一次,看看它是否适合你。

    【讨论】:

      【解决方案3】:

      您正在读取两个值。每次您拨打scanf,程序都会等待您输入内容。由于您两次调用scanf(一次在if 语句之前,一次在if 语句中),您正在等待读取两个值。使用这样的东西:

      int main(void)
      {
          int x;
          printf("please enter a value for x");
          int valueCount = scanf("%d", &x);
      
          if (valueCount == 1) // checks to see if it contains one value
              printf("x value has one value");
          else
              printf("X value is not an integer or has more than one value");
      }
      

      【讨论】:

        【解决方案4】:

        scanf 返回匹配的项目数,或 EOF。但它也需要在每次调用时输入。所以你需要捕获第一条语句的返回值,而不是再次调用它。

        即用int retval = scanf(...)替换scanf(...)

        那么if(...) 语句应该是if(retval == 1)...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-12
          • 2018-06-09
          • 1970-01-01
          相关资源
          最近更新 更多