--- Karthikeyan M <[EMAIL PROTECTED]> wrote:

> 
> You are using windows is it?? Give fflush(stdin)
> before scanf statement
> in the loop. It'll work
> 
>  
> 
> Regards,
> 
> Karthikeyan M
> 
> Love is magic,
> 
> Rem'ber,
> 
> Magic is an illusion.
> 
>  
> 
> ________________________________
> 
> From: [email protected]
> [mailto:[EMAIL PROTECTED] On Behalf
> Of shahwalishaik
> Sent: Thursday, March 29, 2007 4:21 AM
> To: [email protected]
> Subject: [c-prog] execution of loop unknown number
> of times
> 
>  
> 
> hi there, 
> 
> the book i follow for C language shows that the
> following program is 
> correct. but when i complie and run, it is giving
> odd results. the 
> problem is it is running just once, even if 'y' is
> being entered for 
> the second time. help me find the bug
> 
> /*execution of a loop unknown number of times*/
> 
> main()
> char another='y';
> int num;
> 
> while(another=='y')
> {
> printf("enter a number");
> scanf("%d",&num);
> printf("square of %d id %d", num, num*num);
> printf("want to enter another number? y/n");
> 
>  
> 
> scanf("%c",&another);
> }
> getch();
> }
> 
The problem is the first scanf function. After the
number is entered a '/n' is in the input buffer
following the number and not being cleared. You can
clear this by adding a second variable to the scanf to
accept the '/n' character.

scanf("%d%c",&num, &ch);

Now the next scanf will not see the '/n' in the input
buffer and work as it should. 

Some people say to flush the input buffer and it will
work - this might be true on SOME implementation but
is not guaranteed to work in ALL instances. The best
solution is to properly handle the input then there is
no need to flush the input buffer.

BTW scanf is a lousy function and should be avoided if
possable



Mickey M.
Construction Partner Inc.
http://www.constructionpartner.com


 
____________________________________________________________________________________
Now that's room service!  Choose from over 150,000 hotels
in 45,000 destinations on Yahoo! Travel to find your fit.
http://farechase.yahoo.com/promo-generic-14795097

Reply via email to