-2

我需要颠倒文件的顺序并输出到另一个文件中。例如,

输入:

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;
}
4

1 回答 1

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;
}
于 2019-02-21T03:36:57.820 回答