Reputation: 31
I am having a very hard time figuring why this is happening. When I compile and run my code on the linux terminal, the scanf()
function appears to work well in the sense that it accepts input, however for some reason it doesn't actually store that value into the designated variable, instead it makes it 1.
I have looked over my code and can't see and issue, but I do lack knowledge in C, so any help is appreciated.
int main() {
int a, b, c, d, e, f;
printf("Please enter the value of a: ");
a = scanf("%d", &d);
printf("a = %d\n", a);
printf("Please enter the value of b: ");
b = scanf("%d", &e);
printf("b = %d\n", b);
printf("Please enter the value of c: ");
c = scanf("%d", &e);
printf("C = %d\n", c);
c = c + b;
printf("C = %d\n", c);
if (a > 1) {
printf("B = %d\n", b);
printf("C = %d\n", c);
} else {
printf("A is smaller or equal to 1 \n");
}
if (b > 3 || c > 3) {
printf("A = %d\n", a);
} else {
printf("B is less than or equal to 3\n");
printf("B = %d\n", b);
printf("C = %d\n", c);
}
}
Help is greatly appreciated.
Upvotes: 0
Views: 520
Reputation: 60150
I think the confusion here is stemming from what variable stores the value scanned in, and what is being returned from scanf()
.
scanf()
is the address where the scanned value will be storedscanf()
is the number of values scanned (or one of a few error codes)With this understanding, take another look at this code:
int a,b,c,d,e,f;
printf("PLease enter the value of a: ");
a = scanf("%d", &d);
printf("a = %d\n",a);
The third line scans a value and stores it in the variable d
(hence the &d
at the end of the scanf()
call). It also stores the number of values scanned into the variable a
. Then, it prints out a
– which, at this point, is 1, since the previous scanf()
call only found one value.
A better pattern would be to scan into the variable you're asking about (so, in this case, passing &a
to scanf()
), then checking the return value for any errors that occurred before proceeding in your program.
Upvotes: 4