Pelles C forum

C language => Beginner questions => Topic started by: Sango on October 06, 2011, 07:22:20 AM

Title: loop
Post by: Sango on October 06, 2011, 07:22:20 AM
#include<stdio.h>
int main()
{
   char choice='y';
   int num;
   while (choice=='y')
   {
         printf("enter a number\n");
         scanf("%d",&num);
         printf("%d\n",num*num);
         printf("enter your choice");
         scanf("%c",&choice);
   }
   return 0;
}
above code should have keep on looping while choice ='y'.
instead it doesn't promote i/p for choice?
i mean
printf("enter a number\n");
scanf("%d",&num);
printf("%d\n",num*num);
printf("enter your choice");
get executed but it doesn't promote for
scanf("%c",&choice);
Title: Re: loop
Post by: AlexN on October 06, 2011, 09:02:50 AM
The problem is, that when you enter the number you finish you input with the "RETURN"-key. This key produce in the input stream a 0x0D (CR) and a 0x0A LF. scanf() reads the input stream until 0x0D. The second scanf() finds the 0x0A and is happy with it and read it. 0x0A is line end mark so scanf() don't have to wait for anything and your choise is 0x0A.

if you insert a getchar() before the second scanf() the 0x0A will be read and the second scanf() works as expected.

I don't like the scanf() function. It the most times it does't what you want. I prefer to read the input with gets(), which reads usually the hole line and analyse the input after with sscanf(). ;)
Title: Re: loop
Post by: TimoVJL on October 06, 2011, 11:04:19 AM
This reads 0x0A LF from stream away
Code: [Select]
scanf("%d%c",&num, &choice);
EDIT:
and this
Code: [Select]
scanf("%d%*c",&num);
Title: Re: loop
Post by: CommonTater on October 06, 2011, 02:18:47 PM
Another trick you can use is to put a leading space in your format string...
Code: [Select]
scanf(" %c", &choice);
The space tells scanf() to skip over invisible characters.
Title: Re: loop
Post by: Sango on October 06, 2011, 02:37:57 PM
thanks everyone