文件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
- 文件I/O例子
- i/o多路复用例子
- I/O流具体例子
- 文件I/O与标准I/O
- 标准I/O、文件I/O
- 文件I/O与标准I/O
- 异步文件 I/O
- 多媒体文件I/O
- 文件I/O
- 文件I/O操作
- 文件I/O操作
- 文件I/O操作
- 文件I/O
- I/O文件库
- 文件I/O
- 文件I/O
- 文件I/O
- 高级文件I/O
- 微信公众开放平台开发03---百度BAE上搭建属于自己的微信公众平台 -JAVA,微信公众开放平台部署到百度云中BASE2.0,进行调试,木有钱买云服务器的亲们试试
- 算法第四周作业
- Android 中Touch(触屏)事件传递机制
- 南阳理工OJ_题目541 最强DE 战斗力
- 产生一个1-100长度为100不重复的数组
- 文件I/O例子
- JAVA中string.repalce()和string.replaceAll()有什么区别?
- 单例模式
- 算法第四次作業
- Area of Polycubes(简单模拟)
- 栈的两种C++实现
- [LeetCode]10.Regular Expression Matching
- The connection to adb is down, and a severe error has occured.
- CSS布局