【问题标题】:What does the scanf function return?scanf 函数返回什么?
【发布时间】:2012-05-15 05:26:27
【问题描述】:

我知道scanf函数的签名是:

int scanf(const char *format, ...)

此函数返回的int 值是什么?

【问题讨论】:

  • @Bulwersator 如果有人看不懂手册页,那么这不是此类问题的论坛。在这种情况下,所有编程语言中都可能有 1000 种函数的返回值 XYZ。这个问题缺乏非常基础的研究,不应该被鼓励。

标签: c scanf


【解决方案1】:

来自man 页面:

NAME
       scanf,  fscanf, sscanf, vscanf, vsscanf, vfscanf 

       ...

RETURN VALUE
       These functions return the number of input items  successfully  matched
       and assigned, which can be fewer than provided for, or even zero in the
       event of an early matching failure.

       The value EOF is returned if the end of input is reached before  either
       the  first  successful conversion or a matching failure occurs.  EOF is
       also returned if a read error occurs, in which case the error indicator
       for  the  stream  (see ferror(3)) is set, and errno is set indicate the
       error.

在您的情况下,scanf() 可以返回 01EOF

【讨论】:

  • scanf() 返回成功扫描和分配的项目数。如果格式字符串为"%s %d %f %*s%n %d",则如果一切正常,则返回 4。 %*s 禁止分配,因此不计入,%n 返回偏移量且不计入。如果您得到 0、1、2 或 3,则说明出现问题。如果没有数据可供读取,或者存在输入错误(不是格式错误,而是“硬件”错误),您只会返回 EOF。使用"%d" 格式,只有一次转换,因此您将得到EOF01
【解决方案2】:

来自scanf

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

【讨论】:

    【解决方案3】:

    我认为您的代码无法正常工作,因为您忘记了 scanf 函数中的“&”..

    int g=0; //init the variable
    int p=scanf("%d",&g);
    

    scanf函数会将输入的值放到g变量地址中。

    【讨论】:

    • 你认为变量为什么需要初始化?
    【解决方案4】:

    从技术上讲,这是 UB(未定义行为)。

    int g;
    int p=scanf("%d",g);
                     ^
    

    您将一个未初始化的整数传递给 scanf 以将其用作要写入的地址。从这一点开始,任何事情都可能发生。您的应用很可能会崩溃。

    【讨论】:

    • 问题(错误地)被编辑了,所以现在所有的答案都是无效的。
    【解决方案5】:

    无论您在 VDU 输入中给出什么,都将转到变量 g,如果成功读取,p 等于 1。

    【讨论】:

      【解决方案6】:

      它将返回 1,因为 scanf 返回成功读取的项目数

      【讨论】:

      • 如果有人输入bbldnai怎么办?那么它肯定不会返回 1。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2022-12-31
      • 2021-08-09
      • 2017-07-16
      相关资源
      最近更新 更多