Aman Arora Aman Arora - 6 days ago 6
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:

#include<stdio.h>

int main()
{
int no,count_neg=0,count_pos=0,count_zero=0;
char ch='y';
clrscr();
do
{
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;
}

Answer

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

  getchar();  
  scanf();  

//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);
    //code

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

Comments