本文程序摘自数据结构与算法分析——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