关于文件输入的问题
#include <iostream>
#include <fstream>
#include <cstdlib>
const int SIZE = 60;
int main()
{
using namespace std;
char filename[SIZE];
ifstream fin;
cout<<"Enter name of data file: ";
cin.getline(filename, SIZE);
fin.open(filename);
if(!fin.is_open())
{
cout<<"Could not open the file "<<filename<<endl;
cout<<"Program terminating.\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
fin>>value;
while(fin.good())
{
++count;
sum += value;
fin>>value;
}
if(fin.eof())
cout<<"End of file reached.\n";
else if(fin.fail())
cout<<"Input terminaed for unknown reason.\n";
if(count == 0)
cout<<"No data processed.\n";
else
{
cout<<"Items read: "<<count<<endl;
cout<<"Sum: "<<sum<<endl;
cout<<"Average: "<<sum / count<<endl;
}
fin.close();
return 0;
}
我文件的内容是11.1,22.2-99.9这9个数,单程序执行时只读入了8个数,调试发现,
while(fin.good())
{
++count;
sum += value;
fin>>value;
}
在最后一次循环时,虽然99.9被成功读入,但循环条件不满足了,请问是什么原因呢, 文件输入
[解决办法]
帮你运行了一下,我这里输出
Enter name of data file: test
End of file reached.
Items read: 9
Sum: 499.5
Average: 55.5