+ 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.

https://code.sololearn.com/crpziKcO13Wk/?ref=app

23rd Feb 2018, 12:53 AM
Nikhar Sachdeva
Nikhar Sachdeva - avatar
4 ответов
+ 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
23rd Feb 2018, 4:37 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
Okay Thank You.. Can we say that "%*c" clears the Input Buffer for next character to be read?
23rd Feb 2018, 11:50 PM
Nikhar Sachdeva
Nikhar Sachdeva - avatar
+ 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
24th Feb 2018, 1:04 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
0
Okay. Got it.
24th Feb 2018, 2:29 AM
Nikhar Sachdeva
Nikhar Sachdeva - avatar