1
votes

I'm really newbie. I use scanf to read from the input and assign it to a variable. When I printf the variable it prints 1 instead of zero. This is my code:

#include <stdio.h>

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

   return 0;
} 
3

3 Answers

3
votes

scanf returns 1 as success:

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

Change this to:

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

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. 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. You can use that to test whether input was successfully processed.

2
votes

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). 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.

You could decide not to use n and then not print it in the error message:

#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.

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. You could define int a = 0; which would avoid that problem (with any choice of int initializer that you like).