Flush Input Buffer C

2.4k views Asked by At

Note: fflush(stdin) did not work.

Problem:
I'm entering numbers in as a while loop using scanf (inb4 depreciated). When I enter one, the buffer fills the rest in with blank lines.

Code:

double input, total;

for(i=0; i<COUNT; i++){
     printf("\nNumber %d: ", i+1);
     scanf("%d", &input);
     total += input;
}
printf("\nAverage: %f\n", total/COUNT);

Output:

Please enter 5 decimal numbers: 
Number 1: 1.0

Number 2: 
Number 3: 
Number 4: 
Number 5: 
Average: 0.000000
2

There are 2 answers

1
duckvader On

Use flushall() before taking the input Also you have used %d to store in double,use %lf, or declare input as int

0
Devolus On
 if(scanf("%d", &input) != 1)
 {
      /* If scanf failed to read a number clear the input buffer */
      while((c = getchar()) != '\n' && c != EOF);
 }