[Courses] C Programming For Absolute Beginners, Lesson 2: Fun With Printf, Scanf, Puts, and Variables
Kathryn Hogg
kjh at flyballdogs.com
Sun Feb 26 20:24:03 UTC 2012
On 2012-02-26 13:29, Femke Snelting wrote:
> Homework finally done + a late thank you for responding to the
> question I had about lesson 1. All clear now!
>
> Out of curiosity: If I give the program some wrong input, like 'no
> thanks' for example, it jumps to conclusions:
>
> The program:
> ===
> #include <stdio.h>
>
> int main()
> {
> int a, b, c;
> puts( "Please enter any number up to three digits:" );
> scanf( "%d", &a );
> printf( "You entered %d. Now enter another number up to three
> digits:\n", a );
> scanf( "%d", &b );
> c = a + b;
> printf("%d + %d = %d\n", a, b, c);
>
> return 0;
> }
> ===
>
> The output:
> ===
> Please enter any number up to three digits:
> no thanks
> You entered -1216996267. Now enter another number up to three digits:
> -1216996267 + 134513929 = -1082482338
> ===
>
> Why does the program not wait for the second user-input when the
> first is of the wrong type?
The secret is in the man page under scanf. In the return value section
it says that scanf returns an int whose value is the number of items
successfully matched and assigned.
So in your case, you're first scanf call with return 0.
you can check for this in your code
int nr = 0;
nr = scanf("%d", &a);
if (nr < 1) {
printf("Error reading input");
return 1;
}
printf("You entered %d ....", a);
> How does the program decide 'b' is 134513929 (it is always the same)?
When you declared "int a, b, c;" you didn't assign them any values so
C says their values are "undefined". They can be anything so never rely
on uninitialized variables having a particular value.
I'm pedantic so I recommend always explicitly initializing variables:
int a = 0, b = 0, c = 0;
--
Kathryn Hogg
http://womensfooty.com
More information about the Courses
mailing list