c - 为什么scanf总是返回1?

标签 c scanf

#include <stdio.h>    

int main() {
    int days = scanf("%d", &days);
    printf("%d", days);
    return 0;
}

无论如何,结果都是 1。

7
1

我已经使用过很多次 scanf 但从未遇到过这种情况。这是怎么回事?

最佳答案

这是正确的,因为 scanf() 返回成功匹配和转换的元素的数量。考虑到您的情况的正确输入,每次您的输入都通过转换,因此您会看到值 1。

需要注意的是,scanf() 不返回扫描的值本身,它将值存储在传递的参数中。

引用 C11,第 §7.21.6.4 章

[...] the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

关于c - 为什么scanf总是返回1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43146375/

相关文章:

c++ - 将代码从 C++ 移植到 C。我如何处理这个基于 vector 和范围的循环

c - 在C中解析多行字符串

c - 一个简单的 while 循环来检查陷入无限循环的输入

c - for循环后scanf

c - fgets 无法读取换行符

c - 给定一个头文件,有没有办法找出它属于哪个库?

ios - 使用Unity3D在iPhone上弹出SMS ViewController

arrays - 将指针数组传递给接受二维数组的函数

c - 如何在 Visual Studio 代码中添加 gtk 库?

c - 为什么我的 C 程序会产生奇怪的 printf 输出?