[Courses] C Programming For Absolute Beginners, Lesson 2: Fun With Printf, Scanf, Puts, and Variables

Damián detaras at gmail.com
Wed Feb 29 00:04:38 UTC 2012


On 02/26/2012 05:24 PM, Kathryn Hogg wrote:
> 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);

Hi all, this is my first message to this list. My name is Damián and I'm 
from Argentina. I work as a sysadmin and have been "windows free" for at 
least, the last 10 years ;)
It's been a long time since I wanted to learn C programming under 
GNU/Linux, and when I knew about this course I didn't doubt and 
subscribed it. I'm really enjoying it :)
Ok, after the introduction, here is my doubt: I understand that the 
first scanf fails if you enter an invalid value (I tried your portion of 
code), but I don't get why that condition makes the second scanf 
automatically behave as if I had entered a value.
Thank you everyone, and particularly to Carla for taking the time to try 
to teach us some good C programming.

Damián

PS: Sorry if my english is not good, english is not my mother tongue :/


More information about the Courses mailing list