读取文本文件里的数字求平均值

#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
const int SIZE=60;
int main()
{
char filename[SIZE];
ifstream infile;
cout<<"enter name of data file:"<<endl;
cin.getline(filename,SIZE);
infile.open(filename);
if(!infile.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;
infile>>value;
while(infile.good())
{

cout<<value<<" "<<endl;
++count;
sum+=value;
infile>>value;

}
if (infile.eof())//看看循环结束的原因是不是因为遇到结束符了
cout<<"end of file reached.\n";
else if(infile.fail())
cout<<"input terminated by data mismatch.\n";
else cout<<"in put terminated for unkown 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;

}
infile.close();

return 0;

}

 

 

结果图片:

 

posted @ 2015-07-13 11:52  sweeeper  阅读(891)  评论(0编辑  收藏  举报