简体   繁体   English

为什么 scanf 不读取零

[英]why scanf doesn't read zero

I'm really newbie.我真的是新手。 I use scanf to read from the input and assign it to a variable.我使用 scanf 从输入中读取并将其分配给一个变量。 When I printf the variable it prints 1 instead of zero.当我 printf 变量时,它打印 1 而不是零。 This is my code:这是我的代码:

#include <stdio.h>

int main()
{
   int a = scanf("%d", &a);
   printf("%d", a);

   return 0;
} 

scanf returns 1 as success: scanf 成功返回 1:

int a = scanf("%d", &a);

Change this to:将其更改为:

int a;
scanf("%d", &a);

int a = scanf("%d", &a); defines a to be initialized with the return value of scanf and asks scanf to put the converted value in a .定义a以使用scanf的返回值进行初始化,并要求scanf将转换后的值放入a This is wrong.这是错误的。 Use:利用:

int a;
scanf("%d", &a);

scanf returns the number of items assigned or EOF if an input failure occurs before the first matching is completed.如果在第一次匹配完成之前发生输入失败, scanf返回分配的项目数或EOF You can use that to test whether input was successfully processed.您可以使用它来测试输入是否已成功处理。

You should be using something like:你应该使用类似的东西:

#include <stdio.h>

int main(void)
{
    int a;
    int n = scanf("%d", &a);
    if (n != 1)
    {
        fprintf(stderr, "Failed to read an integer (%d)\n", n);
        return 1;
    }
    printf("%d\n", a);

    return 0;
}

The variable n allows you to distinguish between EOF (usually -1 ) and "the first data after white space was not part of an integer" ( n will contain 0 ).变量n允许您区分 EOF(通常是-1 )和“空格后的第一个数据不是整数的一部分”( n将包含0 )。 Note that the error message is printed on standard error;请注意,错误消息打印在标准错误上; that's what it is for.这就是它的用途。 You should normally print a newline at the end of output messages.您通常应该在 output 消息的末尾打印一个换行符。

You could decide not to use n and then not print it in the error message:您可以决定不使用n ,然后不在错误消息中打印它:

#include <stdio.h>

int main(void)
{
    int a;
    if (scanf("%d", &a) != 1)
    {
        fprintf(stderr, "Failed to read an integer\n");
        return 1;
    }
    printf("%d\n", a);

    return 0;
}

It is still important to test the result from scanf() so that if the user typed zero instead of 0 , you could spot the problem.测试scanf()的结果仍然很重要,这样如果用户输入zero而不是0 ,您就可以发现问题。

Note that a would not be assigned if the matching fails — so without the test, you'd be printing an uninitialized variable, which is not a good idea.请注意,如果匹配失败,则不会分配a ——因此,如果没有测试,您将打印一个未初始化的变量,这不是一个好主意。 You could define int a = 0;你可以定义int a = 0; which would avoid that problem (with any choice of int initializer that you like).这将避免该问题(使用您喜欢的任何int初始化程序选择)。

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

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