在我的程序中使用eof然后不断循环为什么?

use*_*373 2 c++ infinite-loop while-loop eof

可能重复:
为什么循环条件中的iostream :: eof被认为是错误的?

这是我编译的程序,除了使用eof的while循环之外的所有内容都变得无限,文件scores.dat包含20个随机数的列表.为什么eof不起作用并使其循环不断???

#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;

}
Run Code Online (Sandbox Code Playgroud)

111*_*111 5

EOF不是唯一的失败标志.如果其中一个(例如fail(转换)标志)被设置,那么它就会循环.

而是试试这个:

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

这是执行此操作的惯用方法,extractin运算符返回对流的引用,只要所有它的失败位都未设置,则流的计算结果为真.

编辑:虽然我在这里注意+= operator和构造函数ifstream.