0

Why while loop is exiting without asking for the value of another, even in the for loop the value of another is not being set .

#include<stdio.h>
    int main(){
            char another ='y';
            int num = 0;
            int i =0;
            /*for(;another =='y'||another =='Y';i++){
                    scanf("%d",&num);
                    printf("%d",num);
                    printf("Enter another num?");
                    scanf("%c",&another);
            }*/
            while(another == 'y'|| another == 'Y'){
                    scanf("%d",&num);
                    printf("%d",num);
                    if(another == 'y'||another =='Y')
                            scanf("%c",&another);
            }
    return 1;
    }
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
Hariom
  • 75
  • 7
  • 2
    `scanf("%c",&another);`-->`scanf(" %c",&another);` (mind the space ) – user2736738 Feb 04 '18 at 06:13
  • You must check the value returned by `scanf()` to know whether `num` got set to a value. The UI design isn't very elegant, either. The user could type `12y13y14y15n` and the code would sort of work. – Jonathan Leffler Feb 04 '18 at 06:16

2 Answers2

1

When you input num, it leaves behind newline \n character. The second scanf() reads the newline left behind by the first scanf().

Hence your program doesn't wait for your input another as it already received \n as the input which will lead to exit of your while loop.

To fix this, change:

scanf("%c",&another);

To:

scanf(" %c",&another);

Note the leading whitespace in the format string " %c" will make scanf consume the newline character thereby fixing your problem.

Refer this Answer for more such scenarios.

Santosh A
  • 5,173
  • 27
  • 37
0

Just put fflush(stdin) before scanf() line. And Include stdlib.h header file.

  • Flushing stdin is implementation specific at best. – Yunnosch Feb 04 '18 at 07:29
  • Sry but I can't understand what you say. @Yunnosch – Samarth patel Feb 04 '18 at 11:01
  • Flushing is only defined for outputs, not for input. If your environment does anything seemingly reliable and useful when you flush your input, then it is just that: Your environment (i.e. not necessarily any other) only seems to do something useful and might not even do it reliably. – Yunnosch Feb 04 '18 at 16:03