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

Damián detaras at gmail.com
Wed Feb 29 02:06:24 UTC 2012


On 02/28/2012 09:21 PM, Jacinta Richardson wrote:
> We're asking scanf() to get us one integer (that's what the %d) is 
> matching.  If it successfully is able to find us one integer, it will 
> have a return value of 1.  If it matches no integers, it will have a 
> return value of 0.  As 0 is less than 1, the condition
>
>     if(nr < 1)
>
> will be true, and we'll enter the block.  This prints out a message 
> and then returns 1;.  The return() function in this case is 
> essentially the same thing as what scanf() is using under the hood, 
> and so our main() function is returning 1, which in this case counts 
> as a failure.  Our program did not run successfully to completion.

Hi Jacinta, thanks for your answer. I understood all of that (I think), 
but I still don't get why in the original code:

====
scanf( "%d", &a );
puts( "Please enter another number up to three digits: " );
scanf( "%d", &b );
c = a + b;
printf("%d + %d = %d\n", a, b, c);
====

If you enter an invalid value in the first scanf, all the other lines 
are run, except for the second 'scanf'. It doesn't wait for user input. 
I don't see the relation between the first scanf returning 0 and the 
second not running because of that condition.

I hope I am clear now.

Thanks in advance,
Damián


More information about the Courses mailing list