C++ 以相反的顺序输出文本文件

C++ Outputting a text file in reverse order

本文关键字:输出 文本 文件 顺序 C++      更新时间:2023-10-16

对于我正在编写的这个程序,我应该从命令行接收一个文本文件,反转文件中所有内容的顺序,然后将文本输出到一个新的文本文件中,并附加"-reverse"。我遇到的问题是颠倒行的顺序。我已经能够反转文本,但我需要帮助反转行。我已经看到了关于使用向量的建议,但我仍然是 c++ 的新手,我相信我不应该只使用高级向量 io 例如,文件名.txt包含:

美国广播公司

法国电力公司

DFG

文件名反转.txt应包含:

GFD

外商直接开发

中央广播公司

我的只包含:

中央广播公司

外商直接开发

GFD

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
/**
* Reverses the line
*/
void reverseStr(string& x)
{
reverse(x.begin(), x.end());
}
int main(int argc, char *argv[])
{
string filename = argv[1];
string filenameCopy = filename;
string reverse = "-reverse";
string reverseFileName;
string reverseLine;
if(filename.rfind(".txt"))//inserts -reverse into existing file name
{
reverseFileName = filenameCopy.insert(filenameCopy.length() - 4,reverse);
} 
string line;
ifstream myfile (filename);
ofstream out(reverseFileName);
if (myfile.is_open())
{
/*
vector<string> lines_in_reverse;
while(getline(myfile,line))
{
lines_in_reverse.insert(lines_in_reverse.begin(), line);
}
*/
while(getline(myfile,line))
{
cout << line << endl;
reverseStr(line);
cout << line << endl;
out << line << endl;
}
myfile.close();
}
else 
{
cout << "Unable to open file";
}
return EXIT_SUCCESS;
}//main

操作简单;只需将整个文件读入std::string,然后以相反的顺序(从rbegin()rend()(迭代字符串,并打印每个字符。