NO

Author Topic: loop  (Read 3394 times)

Sango

  • Guest
loop
« 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);

Online AlexN

  • Global Moderator
  • Member
  • *****
  • Posts: 394
    • Alex's Link Sammlung
Re: loop
« Reply #1 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(). ;)
best regards
 Alex ;)

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
Re: loop
« Reply #2 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);
« Last Edit: October 06, 2011, 03:30:08 PM by timovjl »
May the source be with you

CommonTater

  • Guest
Re: loop
« Reply #3 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.

Sango

  • Guest
Re: loop
« Reply #4 on: October 06, 2011, 02:37:57 PM »
thanks everyone