大家好,本人刚开始用c++ primer plus 中文版第五版学习c++,其中一个例程,书中的程序清单6.16,本人打了这个代码之后每次读取txt文件时总是不能读取到最后一个数字,程序如下:
#include <iostream>
#include <fstream>
#include <cstdlib>
const int SIZE=60;
int main()
{
using namespace std;
char filename[SIZE];
ifstream in_file;
cout<<“enter name of data file:”;
cin.getline(filename,SIZE);
in_file.open(filename);
if(!in_file.is_open())
{
cout<<“could not open the file:”;
cout<<“program terminating”;
exit(EXIT_FAILURE);
}
double value;
double sum=0.0;
int count=0;
in_file>>value;
while(in_file.good() )
{
++count;
sum+=value;
in_file>>value;
}
if(in_file.eof()) cout<<“end of file reached.\n”;
else if(in_file.fail()) cout<<“input terminated by data mismatch.\n”;
else cout<<“input terminated for unknown reason.\n”;
if(count==0) cout<<“NO data int the file”;
else
{
cout<<“items read:”<<count<<endl;
cout<<“sum: ”<<sum<<endl;
cout<<“Average: “<<sum/count<<endl;
}
in_file.close();
return 0;
}
txt文件内容及运行结果如图,总是没有读到最后一个数字,恳请知道答案的前辈指点一下,感激不尽
#include <iostream>
#include <fstream>
#include <cstdlib>
const int SIZE=60;
int main()
{
using namespace std;
char filename[SIZE];
ifstream in_file;
cout<<“enter name of data file:”;
cin.getline(filename,SIZE);
in_file.open(filename);
if(!in_file.is_open())
{
cout<<“could not open the file:”;
cout<<“program terminating”;
exit(EXIT_FAILURE);
}
double value;
double sum=0.0;
int count=0;
in_file>>value;
while(in_file.good() )
{
++count;
sum+=value;
in_file>>value;
}
if(in_file.eof()) cout<<“end of file reached.\n”;
else if(in_file.fail()) cout<<“input terminated by data mismatch.\n”;
else cout<<“input terminated for unknown reason.\n”;
if(count==0) cout<<“NO data int the file”;
else
{
cout<<“items read:”<<count<<endl;
cout<<“sum: ”<<sum<<endl;
cout<<“Average: “<<sum/count<<endl;
}
in_file.close();
return 0;
}
txt文件内容及运行结果如图,总是没有读到最后一个数字,恳请知道答案的前辈指点一下,感激不尽
解决方案
40
已经读到了啊,你算一下12个数的和是不是186,是你的count有问题,原因是循环前已经读了一个数了,所以count应该从1开始