2

Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?

Here is my program it compiles and everything but the while loop with eof becomes infinite the file scores.dat contains a list of 20 random numbers. Why does the eof not work and makes it loop continuously???

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

int main ()
{

  int x, sum = 0, count = 0;
  double answer;
  ifstream  y;

  y.open("scores.dat");
  while (!y.eof())
   {
     y >> x;
     sum = sum + x;
     count ++;
     cout << x << endl;
   }

  answer = sqrt (((pow(x, 2.0)) - ((1.0/count) * (pow(x, 2.0)))) / (count - 1.0));
  cout << answer;

}
Community
  • 1
  • 1
  • 2
    Here's another reason to never use `.eof()` as a loop condition: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Robᵩ Oct 24 '12 at 18:48

1 Answers1

5

EOF is not the only fail flag. If one of the others (such as the fail (to convert) flag) gets set then it's just going to loop round.

instead try this:

std::ifstream y("scores.dat");
while (y >> x) {
    sum += x;
    ++count;
    std::cout << x << std::endl;
}

This is the idiomatic way to do this, the extractin operator return the a refrence to the stream, the stream evaluates as true so long as all it's fails bits are not set.

EDIT: Whilst I am here note the += operator and constructor for ifstream.

111111
  • 14,528
  • 6
  • 38
  • 58