0

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
Goodies
  • 3,526
  • 2
  • 22
  • 45

2 Answers2

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

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

duckvader
  • 71
  • 12