简体   繁体   English

使用scanf函数为变量分配值

[英]Assigning a value to a variable with the scanf function

No matter what value I enter for x, the output for the value of y is always 1. Any ideas why? 无论我为x输入什么值,y的输出始终为1。为什么?

#include <stdio.h>    
int main() {
    int x, y;
    y = scanf("%d", &x);
    printf("y = %d\n", y);
    return 0;
}

From scanf(3) - Linux man page : scanf(3)-Linux手册页

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. 这些函数返回成功匹配和分配的输入项的数量,该数量可能少于所提供的数量,在早期匹配失败的情况下甚至为零。

Since scanf return value is the number of items written (in your case, 1, since only 1 int was scanned), not the integer value of the scanned character 由于scanf返回值是写入的项目数(在您的情况下为1,因为只扫描了1个int ),而不是所扫描字符的整数值

int main() {
    int x, y, z, n;
    n = scanf("%d", &x);
    printf("n = %d\n", n);                 // prints 1
    n = scanf("%d%d", &x, &y);
    printf("n = %d\n", n);                 // prints 2
    n = scanf("%d%d%d", &x, &y,&z);
    printf("n = %d\n", n);                 // prints 3
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM