如何借助与string ifstream按行读取文件
来源:互联网 发布:f=ma 知乎 编辑:程序博客网 时间:2024/06/03 18:22
#include <iostream>#include <iterator>#include <fstream>#include <algorithm>#include <vector>using namespace std;class myline : public string {};istream& operator>>(istream& is, myline& line){ getline(is, line); return is;}int main(){ ifstream fin("./testkill.cpp"); istream_iterator<myline> begin(fin); istream_iterator<myline> end; vector<string> content; copy(begin, end, back_inserter(content)); cout << "content" <<endl; copy(content.begin(), content.end(), ostream_iterator<string>(cout, "\n")); return 0;}
上面的代码按行读取文件.下面的是按字符串读取文件:
#include<iostream>#include<iterator>#include<fstream>#include<algorithm>#include<vector>using namespace std;int main(){ifstream fin("../code_1/ut/testkill.cpp");istream_iterator<string> begin(fin);istream_iterator<string> end;vector<string> content;copy(begin,end,back_inserter(content));cout<<"content:"<<endl;copy(content.begin(),content.end(),ostream_iterator<string>(cout,"\n"));return 0;}t
感兴趣的可以测试一下上述的代码对比一下结果.
问题在与迭代器的类型:下面的是string的迭代器,迭代器每次读取一个单词,即按空格截断文件流,上面我们继承了string且重载了<< (插入)运算符,我们每次从流中读取一行(getline),这样在:
copy(begin,end,back_inserter(content));时每次迭代器就从数据流读取一行push_back进去到vector中.所以最终从vector中读取的就是一行一行的文件数据.
阅读全文
0 0
- 如何借助与string ifstream按行读取文件
- ifstream按行读取文件内容
- C++中string类及文件流类(ofstream,ifstream)的基本操作---按行读取文档
- ifstream多次读取文件
- ifstream读取文件
- ifstream多次读取文件
- ifstream操作文件读取
- ifstream文件无法读取
- ifstream 和 getline 读取文件
- 读取文件:ifstream和getline
- ifstream读取文件的坑
- ifstream读取文件和stringstream读取内容
- C++ ofstream ifstream 按行读写文件
- 使用ifstream和getline读取文件内容
- c++使用getline和ifstream读取文件
- c++使用getline和ifstream读取文件
- 使用ifstream和getline读取文件内容
- 使用ifstream和getline读取文件内容
- Swift 艺术二维码生成库,可添加各种奇怪的样式
- 软件回归测试及其实践
- 小程序开发中的各种汇总
- hdoj-2564-词组缩写(解题报告)
- 算法竞赛入门经典 习题5-5 复合词 UVa10391
- 如何借助与string ifstream按行读取文件
- 【hdu 1213】How Many Tables
- jboss中调用webservice时报java.lang.RuntimeException: Cannot create a secure XMLInputFactory的异常
- AAC音频格式简介
- Volley的使用
- log4cpp 编译安装
- kvm安装及简单使用
- Visual Studio Code 使用Git进行版本控制
- 卷积神经网络之SoftMax函数