Aman Arora Aman Arora - 1 year ago 68
C Question

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

So I'm working on basic C skills, and I want to design a code which enters as many numbers as the user wants. Then, it should display the count of positive,negative & zero integers entered.
I've searched Google & StackOverflow. The code seems fine according to those programs.
It compiles & runs. But whenever I input anything after the prompt "enter more? y/n", it returns to the code..
Please have a look at the code below:


int main()
int no,count_neg=0,count_pos=0,count_zero=0;
char ch='y';
puts("Enter number");
if (no>0)
else if (no<0)
puts("want more? - y/n ");
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);

return 0;

Answer Source

The problem is with "scanf("%c", &ch);"

What happens actually is :
Suppose you enter 'y' as a choice and hit 'enter'(return), the return is a character and
its character value is 10(since its a new line character), thus the scanf takes the 'return' as its input and continues.

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

// your code


//your code
getchar() takes the return value as its input, thus you are left with your actual value.

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

when scanf() encounters the '\n' character it skips it (google about scanf, to know how
and why ), thus stores the intended value inside 'ch'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download