[C++][文本操作]逐行读取文本并倒序输出

Cplusplus
回复
头像
vicyang
版主
版主
帖子: 56
注册时间: 2016年07月21日 20:35
联系:

[C++][文本操作]逐行读取文本并倒序输出

帖子 vicyang »

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;
int main(int argc, char *argv[] )
{
string fname="read_line.cpp";
vector<string> lines;
string a;
ifstream fh( fname.c_str() );
if (!fh) cerr<<"can't open input file"<<endl;

while ( getline(fh, a) )
lines.push_back(a);

for (int i=lines.size()-1; i>=0; i--)
cout << lines[i] << endl;

fh.close();
return 0;
}
正在学 ;)

输出结果:
} return 0; fh.close(); cout << lines << endl; for (int i=lines.size()-1; i>=0; i--) lines.push_back(a); while ( getline(fh, a) ) if (!fh) cerr<<"can't open input file"<<endl; ifstream fh( fname.c_str() ); string a; vector<string> lines; string fname="read_line.cpp"; { int main(int argc, char *argv[] ) using namespace std; #include <vector> #include <fstream> #include <string> #include <iostream> (这里会多一个换行)


发现:getline会吃掉换行符,需要自己添加"\n"(可能导致结果不是原汁原味的),然后在倒序输出时,原本的“第一行”就多了个换行。
考虑:如果文件不大,可以尝试全部读进buffer,按 "\r\n"或者 "\n" 切割,然后反向获取并输出。

问题延伸:
如果文件达到10G,如何在控制在低内存占用的情况下逆序输出?

暂时考虑用 seek 操作,未完待续
头像
vicyang
版主
版主
帖子: 56
注册时间: 2016年07月21日 20:35
联系:

Re: [C++][文本操作]逐行读取文本并倒序输出

帖子 vicyang »

以前怕不是对C++有什么误解,以为特别难用。发现迭代器用起来也很爽:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void print(int n) { cout << n << endl; }

int main(int argc, char *argv[] )
{
vector<int> arr(5,1);
for_each( arr.begin(), arr.end(), print );
return 0;
}
又学了一下,可以用匿名函数了,逆序输出
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main(int argc, char *argv[] )
{
vector<int> arr({1,2,3,4,5});
for_each( arr.rbegin(), arr.rend(), [](int n) { cout<<n<<endl; } );
return 0;
}
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 1 访客