+ 1
I want user to give inputs and count no. Of zeroes,(+)ves,(-)ves entered..But it is taking just one i/p and displays the result.
4 Answers
+ 1
Actually it is the problem with the second scanf which reads the \n read by the first scanf. So the solution is to prompt the second scanf to ignore the first character from the buffer, like this :
scanf("%*c%c",&ans);
/* Here, %*c means discard a
character read earlier. */
So the final code looks like this :
#include<stdlib.h>
#include<stdio.h>
int main()
{
int pos=0,neg=0,zero=0,num; char ans;
do
{
printf("Enter any Number: ");
scanf("%d",&num);
if (num>0) pos++;
else if(num<0) neg++;
else zero++;
printf("\n More numbers? (y/n): ");
scanf("%*c%c",&ans);
fflush(stdin);
} while(ans == 'y');
printf("\n\nNumber of Positives: %d\n Number of Negatives: %d\n Number of Zeros: %d\n", pos, neg, zero);
return 0;
}
For more information, visit : ee.hawaii.edu/~tep/EE160/Book/chap4/section2.1.4.html
+ 1
Okay Thank You..
Can we say that "%*c" clears the Input Buffer for next character to be read?
+ 1
It does not clear the buffer completely, but removes just a single character from it.
Eg :
If the buffer at sometime was = Hello\n
Buffer after a single %*c operation = Hello
0
Okay. Got it.