码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-13 13:50:50      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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

}

 

 

结果图片:

 

技术分享

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

标签:

原文地址:http://www.cnblogs.com/sweeeper/p/4642506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!