文件I/O例子

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值