【问题标题】:Strange output on using scanf使用 scanf 的奇怪输出
【发布时间】:2011-04-22 09:32:28
【问题描述】:
#include <cstdio>  

int main()  
{  
    int i;
    printf("%d", scanf("%d", &i));
}

无论我输入什么数字,我都会得到输出:

1

为什么会这样?

【问题讨论】:

  • &lt;cstdio&gt; 是 C 标准标头。
  • @DeadMG- 你太可笑了。 Each header from the C Standard Library is included in the C++ Standard Library under a different name, generated by removing the .h, and adding a 'c' at the start。这个问题是 C 和 C++ 特定的。

标签: c++ c scanf


【解决方案1】:

成功时,scanf 函数

返回成功读取的项目数。

如果发生匹配失败,此计数可以匹配预期的读数数量或更少,甚至为零。 如果在成功读取任何数据之前输入失败,则返回EOF

也试试这个:

printf("%d",scanf("%d%d",&amp;i,&amp;i));

【讨论】:

  • OP可能想要输入的数字,scanf返回后将在'i'中。
  • 不,我觉得他不知道scanf到底返回了什么。
【解决方案2】:

你输出scanf的结果,不是你输入的数字,而是成功读取的项目数。您输入的数字存储在 i 中。要输出它,您必须多写一行:

#include <cstdio>  

int main()  
{  
   int i;
   if (scanf("%d",&i) == 1)
       printf("%d", i);
}

【讨论】:

  • S.O. 中有太多未经验证的输入。问题,也不要在答案中使用它! - 好多更好的说if (scanf("%d", &amp;i) == 1) printf("%d\n", i);
  • 根据您的建议编辑。
  • 好吧,那我最好给你一个 +1 ;-)。干杯。
【解决方案3】:

scanf() 成功时返回读取的项目数。这里它只读取一个数字,因此无论数字如何,每次输出都是 1。

【讨论】:

    猜你喜欢
    • 2015-06-17
    • 2021-03-12
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多