c - do-while loop "enter more (y/n)" - character issue -


so i'm working on basic c skills, , want design code enters many numbers user wants. then, should display count of positive,negative & 0 integers entered. i've searched google & stackoverflow. code seems fine according programs. compiles & runs. whenever input after prompt "enter more? y/n", returns code.. please have @ code below:

#include<stdio.h>  int main()  {     int no,count_neg=0,count_pos=0,count_zero=0;     char ch='y';     clrscr();         {         puts("enter number");         scanf("%d",&no);         if (no>0)             count_pos++;         else if (no<0)             count_neg++;         else             count_zero++;         puts("want more? - y/n ");         scanf("%c",&ch);     }     while (ch=='y');      if (ch=='n')     {         printf("no of positives = %d",count_pos);         printf("no of negatives = %d",count_neg);         printf("no of zeros = %d",count_zero);     }      getch();     return 0; } 

the problem "scanf("%c", &ch);"

what happens :
suppose enter 'y' choice , hit 'enter'(return), return character and
character value 10(since new line character), scanf takes 'return' input , continues.

solution : 1. use getchar() before scanf()

// code

  getchar();     scanf();   

//your code
getchar() takes return value input, left actual value.

  1. add '\n' scnaf()
    // code
    scanf("\n%c", &ch);
    //code

when scanf() encounters '\n' character skips (google scanf, know how
, why ), stores intended value inside 'ch'.


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -