使用输入输出流迭代器读取和写入文件
来源:互联网 发布:java和php哪个前景好 编辑:程序博客网 时间:2024/05/21 14:47
目标1:使用istream_iterator读取一个文件的内容(为数字),使用ostream_iterator将奇数写入第一个文件中,每个值之后都跟一个空格;将偶数写入第二个文件中,每个值占一行。
#include<iostream>#include<vector>#include<string>#include<iterator>#include<fstream>int main(){ ifstream infile("numbers.txt");//创建文件输入流,指向numbers.txt,此文件需要首先保存在工程目录下 ofstream outfile_1("jishu.txt");//创建文件输出流1,指向jishu.txt ofstream outfile_2("oushu.txt");//创建文件输出流2,指向oushu.txt if(!infile|!outfile_1|!outfile_2)//检查文件是否存在 { cout<<"file does't exist !"<<endl; return -1; } istream_iterator<int> in_iter(infile),eof;//创建输入流迭代器,指向infile,eof用于判断文件末尾 ostream_iterator<int> out_iter_1(outfile_1," ");//创建输出流迭代器,每个元素后跟空格 ostream_iterator<int> out_iter_2(outfile_2,"\n");//创建输出流迭代器,每个元素后跟换行 vector<int> vec(in_iter,eof);//将输入流读取的文件内容复制到vec中 for(auto p=vec.begin();p!=vec.end();p++) { if(*p%2==1)//数据为奇数 copy(p,p+1,out_iter_1); else//数据为偶数 copy(p,p+1,out_iter_2); } system("pause"); return 0;}
目标2:读取一个文档中单词出现的次数,要求使用关联容器map.
#include<iostream>#include<map>#include<string>#include<fstream>#include<iterator>using namespace std;int main(){ map<string,size_t> word_count;//创建关联容器 string word; ifstream ifile("words.txt");//打开文件 if(!ifile)//对文件进行检查 { cout<<"Can't open the file!"<<endl; exit(0); } istream_iterator<string> iter(ifile),eof;//创建输入流迭代器,指向打开的文件 auto p=iter; while(p!=eof)//遍历文件,对单词进行计数 { word=*p++; ++word_count[word]; } for(auto w=word_count.begin();w!=word_count.end();w++) cout<<w->first<<" occurs "<<w->second<<((w->second>1)?" times":" time")<<endl;//向屏幕输出每个单词出现的次数 system("pause"); return 0;}
测试时先要在工程目录先新建words.txt文件
阅读全文
0 0
- 使用输入输出流迭代器读取和写入文件
- 使用 JDOM 读取和写入 XML 文件
- 使用Python读取和写入CSV文件
- 使用JAVA读取和写入EXCEL文件
- 使用Python读取和写入CSV文件
- C#文件写入和读取简单使用
- 使用JAVA读取和写入EXCEL文件
- 文件读取和写入
- 文件读取和写入
- 文件读取和写入
- 读取文件和写入文件
- 文件的读取和写入
- 读取和写入plist文件
- 写入和读取顺序文件
- 读取和写入plist文件
- ******************* 文件的写入和读取 *******************
- 【OpenMesh】文件读取和写入
- 文件的读取和写入
- BZOJ2244 & Codevs1822 [SDOI2011]拦截导弹
- Linux Shell Scripting Cookbook, Second Edition [eBook] pdf,epub,mobi,code
- cs231n-2017-assignments2-TensorFlow.ipynb 自动调参
- Java中单例模式实现
- node.js
- 使用输入输出流迭代器读取和写入文件
- 2017暑期集训一Restoring Painting(思维)
- js校验页面输入是否为空
- 内存映射
- LSTM
- 2016web前端面试题
- Html5(移动端)开发,安卓机上的软键盘顶起影响页面布局
- Linux SPI总线和设备驱动架构之四:SPI数据传输的队列化
- jenkins 构建maven工程--Unknown lifecycle phase "clean"