C++ 在我的程序中使用eof,然后不断循环,为什么?
可能重复:C++ 在我的程序中使用eof,然后不断循环,为什么?,c++,while-loop,infinite-loop,eof,C++,While Loop,Infinite Loop,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
这是我的程序,它编译和一切,但与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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
整数x,和=0,计数=0;
双重回答;
ify;
y、 开放(“scores.dat”);
而(!y.eof())
{
y>>x;
sum=sum+x;
计数++;
coutEOF并不是唯一的失败标志。如果其他标志之一(如fail
(转换)标志)被设置,那么它只是循环
相反,请尝试以下方法:
std::ifstream y("scores.dat");
while (y >> x) {
sum += x;
++count;
std::cout << x << std::endl;
}
std::ifstreamy(“scores.dat”);
而(y>>x){
总和+=x;
++计数;
std::cout还有一个不使用.eof()
作为循环条件的原因: