【问题标题】:C++ Outputting a text file in reverse order [duplicate]C ++以相反的顺序输出文本文件[重复]
【发布时间】:2017-07-11 17:09:42
【问题描述】:

对于我正在编写的这个程序,我想从命令行获取一个文本文件,颠倒文件中所有内容的顺序,然后将文本输出到一个带有“-reverse”的新文本文件中给它。我遇到的问题是颠倒行的顺序。我已经能够反转文本,但我需要帮助反转线条。我已经看到有关使用向量的建议,但我对 c++ 还是很陌生,我相信我不应该只使用高级 io 的向量 例如,filename.txt 包含:

abc

edf

dfg

filename-reverse.txt 应包含:

gfd

fde

cba

我的只包含:

cba

fde

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

【问题讨论】:

  • 您可以将所有线条放入一个向量中,然后像处理线条一样在其上反向运行。

标签: c++ io


【解决方案1】:

做起来很简单;只需将整个文件读入std::string,然后以相反的顺序(从rbegin()rend())遍历字符串,然后打印每个字符。

【讨论】:

    猜你喜欢
    • 2022-11-28
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2013-05-29
    相关资源
    最近更新 更多