文件I/O例子

来源:互联网 发布:会计数据的特点是 编辑:程序博客网 时间:2024/06/07 19:55

本文程序摘自数据结构与算法分析——C++语言描述(第2版) p189-191

这个程序对文件输入输出流的操作简练明了,故摘下来与大家分享。
(如涉及版权,请联系我,我会及时删除)


/*---------------------------------------------------读取存储在文件中的数值,计算最小值、最大值和这些数的平均值,并将这些统计信息写到一个输出文件中输入(键盘):输入和输出文件的名字输入(文件):一个数值序列输出(文件):值的个数、最小值、最大值和平均值----------------------------------------------------*/#include <iostream>#include <string>#include <fstream>#include <cassert>#include <cfloat>using namespace std;int main(){cout<<"Enter the name of the input file: ";string inputFileName;getline(cin,inputFileName);ifstream fin;fin.open(inputFileName.data());    //打开一个文件assert(fin.is_open());     //判断文件是否打开int count = 0;double reading, maximum = DBL_MIN, minimum = DBL_MAX,sum = 0.0;for(;;)    {fin>>reading;          //从文件中读取数字if(fin.eof()) break;   //判别结束退出count++;sum+=reading;          //求和if(reading< minimum)   //求最小值minimum = reading;if(reading> maximum)   //求最大值maximum = reading;}fin.close();               //关闭程序cout<<"enter the name of the output file: ";string outputFileName;getline(cin,outputFileName);ofstream fout(outputFileName.data());   //打开输出文件assert(fout.is_open());fout<<"\n--There were "<<count<<" values";   //输出信息if(count>0)fout<<"\n reanging from "<<minimum<<" to"<<maximum<<"\n and their average is "<<sum/count<<endl;fout.close();cout<<"Processing complete.\n";}

输入文件:data1.txt

88 86 99 100
77 66 44 55
95 85

输出文件:data2.txt

--There were 9 values
reanging from 44 to100
and their average is 78.8889


0 0
原创粉丝点击