# Scanf in C language

• 11-28-2012
vicky2
Scanf in C language
Suppose that we call scanf as follows:
scanf(“%d%f%d”, &i, &x, &j);
If the user enters
10.3 5 6
what will be the values of i, x and j after the call? (Assume that i and j are int variables and x
is a float variable).
• 11-28-2012
vicky2
Scanf in C language
Suppose that we call scanf as follows:
scanf(“%f%d%f”, &x, &i, &y);
If the user enters
12.3 45.6 789
what will be the values of x, i and y
• 11-28-2012
Salem
So perhaps you should create a small C program and try each one and see the results.
• 11-28-2012
vicky2
Well i tried but i am not sure if my results are correct..... I have been told these questions are tricky so please someone can help me out to see hwta the final and correct results will be.THANKS
• 11-28-2012
Salem
> Well i tried but i am not sure if my results are correct

> ..... I have been told these questions are tricky
They're not tricky at all.
• 11-28-2012
vicky2
100.3000005
• 11-28-2012
qny
Quote:

Originally Posted by vicky2
scanf(“%d%f%d”, &i, &x, &j);
If the user enters
10.3 5 6

i = 10
x and j have indeterminate values and cannot be used
Also, the return value from that scanf() call was 1 to let you know only 1 assignment was made.

Quote:

Originally Posted by vicky2
scanf(“%f%d%f”, &x, &i, &y);
If the user enters
12.3 45.6 789

x = 12.3
i = 45
y is indeterminate and cannot be used.
Also, the return value from that scanf() call was 2 to let you know only 2 assignments were made.

~~~~~~~~

Remember to always test the return value of scanf()
Code:

`if (scanf("%f%d%d", &x, &i, &j) != 3) /* error */;`
• 11-28-2012
Salem
Quote:

Originally Posted by vicky2
100.3000005

It might be worth printing out some newlines or other white-space between each number.

printf("%d\n%f\n%d\n", i, x, j);
rather than
printf("%d%f%d\n", i, x, j);
• 11-28-2012
qny
Oops ... my bad at post #7

first scanf gets 10, 0.3, and 5 (and keeps " 6" in the buffer)
second scanf gets 12.3, 45, and 0.6 (and keeps " 789" in the buffer)