[英]How to reverse the order of a input file using C++?
我需要颠倒文件的顺序并输出到另一个文件中。 例如,
输入:
hello
this is a testing file again
just so much fun
预期输出:
just so much fun
this is a testing file again
hello
这是我当前的代码,它打印到颠倒行顺序以及每个单词字符顺序的位置。
当前的:
nuf hcum os tsuj
niaga elif gnitset a si siht
olleh
int print_rev(string filename, char c){
ifstream inStream (filename);
ofstream outStream;
inStream.seekg(0,inStream.end);
int size = inStream.tellg();
outStream.open("output.txt");
for (int j=1; j<=size; j++){
inStream.seekg(-j, ios::end);
c=inStream.get();
outStream << c;
}
inStream.close();
outStream.close();
return 0;
}
您正在一个字符一个字符地反转整个文件。 你要做的是分别读取每一行,然后颠倒行序。
一堆行似乎是一个不错的选择:
int printRev(string filename)
{
stack<string> lines;
ifstream in(filename);
string line;
while (getline(in, line))
{
lines.push(line);
}
ofstream out("output.txt");
while (!lines.empty())
{
out << lines.top() << endl;
lines.pop();
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.