【问题标题】:About Ovewriting variables in scanf()关于在 scanf() 中覆盖变量
【发布时间】:2020-03-13 23:36:22
【问题描述】:

我正在创建一个测试程序,当输入的数字小于或等于十时会显示错误消息:

#include <stdio.h>

void errorMessage()
{
   printf("\n This number is less than, or equal to, 10. Please try again. ");
}

int main()
{
   int a;
   printf("\n Enter a number that is greater than 10. ");
   while(scanf(" %d",&a) <= 10)
   {
      errorMessage();
      printf("\n Enter a number that is greater than 10. ");
   }
   printf("\n This number is greater than 10.");
   return 0;
}

当输入小于或等于十的数字(eg 5),然后输入大于十的数字(eg 15)时,问题就来了然后。即使该数字使while 语句为假,程序也会执行errorMessage()。我发现scanf() 以某种方式存储了int a 的输入值。我想知道如何在程序再次运行while 循环之前清除int a 的输入。

【问题讨论】:

  • 注意:" " 格式在这里没有用处。

标签: c loops caching while-loop scanf


【解决方案1】:

scanf() 不返回 scanned 值,它返回匹配并成功存储的输入数。

引用C11,第 7.21.6.4 章(强调我的

如果之前发生输入失败,scanf 函数将返回宏 EOF 的值 第一次转换(如果有)已完成。否则,scanf 函数返回 分配的输入项的数量, 可以少于提供的数量,甚至为零,在 早期匹配失败的事件。

您需要比较存储在a 中的值,该值作为转换说明符%dscanf() 的参数传递。

您需要两个步骤:

  • 检查scanf()的返回值,确保没有扫描失败。
  • 根据需要检查为输入范围提供的参数中存储的值。

代码的修改版本可能看起来像

#include <stdio.h>

void errorMessageAndCleanup()
{
   printf("Enter a valid number!!\n");
   while (getchar() != '\n');            //cleanup the existing buffer with invalid input
}

int main(void)
{
   int a;
   printf("Enter a number that is greater than 10. \n");
   while(  ! ((scanf(" %d",&a) == 1) && (a > 10)) ) // check for scan success AND 
   {                                                // the scanned value IF success
      errorMessageAndCleanup();
      printf("Enter a number that is greater than 10.\n");
   }
   printf("This number is greater than 10.\n");
   return 0;
}

【讨论】:

    【解决方案2】:

    Sourav Gosh 的回答解释了你做错了什么。解决方案可能是:

    while(scanf(" %d",&a)!=1 || a<= 10)
    

    这首先检查scanf 是否能够读取和转换一个数字,然后检查该数字是否小于或等于 10。

    【讨论】:

    • 注意:如果输入是非数字的(scanf(" %d",&amp;a) 返回 0),这样的测试不消耗非数字文本会导致无限循环。
    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    相关资源
    最近更新 更多