C++ 以相反的顺序输出文本文件
C++ Outputting a text file in reverse order
对于我正在编写的这个程序,我应该从命令行接收一个文本文件,反转文件中所有内容的顺序,然后将文本输出到一个新的文本文件中,并附加"-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()
(迭代字符串,并打印每个字符。
相关文章:
- C++ 以相反的顺序输出文本文件
- 如何在不移动C 中的光标坐标的情况下输出文本以控制特定坐标
- 输出文本文件的位置
- 从输入复制到输出文本文件
- 输入和输出文本文件
- 您如何在输出文本的同时接受用户输入
- 如何从随机数中输出文本
- 使用读取系统调用C++输出文本
- 输出文本C++
- 将输出文本与 cout 对齐到右侧
- 如何在不使用cout/printf的情况下输出文本在cpp和c中
- 用户在输出文本时输入到控制台
- C++每x次输出文本
- outFile C++未写入输出文本
- C++:将输出文本格式化为.doc/.docx/.rtf(第2部分)
- 将输出文本格式化为.doc/.docx
- 从长期运行的控制台应用程序(C++)输入和输出文本
- 主函数不输出文本文件行
- 输出文本文件数据到字符数组
- 如何在c++中输出文本到打印机