abdullah abdullah - 2 months ago 12
C Question

what does it mean to assign a scanf statement to a variable?

I have recently seen an answer that went over my head,
the guy wrote this piece of code and it had the value of 1.

cr
is an integer.

cr = scanf("%d %.2f",&x,&y)


so how can you do so? and why does it give out 1?

Answer

First off, you are obviously gonna get 1 due to the fact there is a problem in that scanf statement. You need to remove .2 from there as @weathervane has stated.

cr = scanf("%d %.2f",&x,&y)

to this:

cr = scanf("%d %f",&x,&y)

When you print cr, you will get a value of 2 instead of 1. You add another var to scan in that scanf statement and print it, you will see a value of 3.

#include <stdio.h>

main(){
    int x, cr, z;
    float y;

    cr = scanf("%d %f %d",&x,&y, &z);
    printf("%d\n", cr);
}

Output:

56
5
2
3

As you could see, cr is storing the number of var being used.