为什么我的 printf 函数 return 不是以下 C 代码中的正确扫描值?

why doesn't my printf function return the correct scanned value in the following C code?

我想扫描一个值,并打印扫描的值

int main()
{
    int n;
    printf("enter value: ");
    n = scanf("%d",&n);
    printf("%d",n);
    return 0;
} 

然而,打印结果给了我 1 而不是 9,如下所示。为什么会这样,我该如何解决?

因为 n 被 scanf

的 return 值覆盖

如果您不想将解析的项目数分配给 n,请使用 scanf("%d", &n);

scanf() 不是 return 它扫描的值,它是 return 成功读取的项目数。输入 &n 是缓冲区的地址,scanf() 用它扫描的内容填充。

直接打电话

scanf("%d", &n);

如果您不想进行任何错误检查。

why doesn't my printf function return the correct scanned value in the following C code?

你错了。 printf 通话

n = scanf("%d",&n);
printf("%d",n);

通过调用 scanf 输出正确的值 return。

根据(7.21.6.4的scanf函数)

3 The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, 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.

作为scanf的调用

n = scanf("%d",&n);

只分配了一项然后它的return值等于1。这个值是你在下一次调用printf时输出的值

printf("%d",n);

如果你想在 scanf 的调用中输出分配的项目,那么不要用 scanf 调用的 return 值覆盖它,例如

scanf("%d",&n);
printf("%d",n);

或者你可以这样写

if ( scanf("%d",&n) == 1 ) printf("%d",n);