C ++如何读取文本文件并反转行,使其从下往上读取

时间:2010-02-22 02:40:56

标签: c++

请帮助我是C ++的新手

使用堆栈实现

我应该阅读一个包含以下内容的示例文本文件:

text file
begining to end
return text

并返回一个文本文件:

return text
begining to end
test file

这是测试实现的示例代码:

#include <iostream>
#include <fstream>
#include <string>
#include "stack1.h"
using namespace std

void reverse (ifstream & infile, ofstream & outfile);  //function prototype

int main () {

ifstream infile;  // declaring a file for input
ofstream outfile; // declaring a file for output
infile.open ("c:\\myInputFile.txt");  

 if (!infile)  { cout << "File could not be opened.  Program terminated." << endl;
           return 1;    // terminates program
         }
 outfile.open ("c:\\myOutfile.txt");
 reverse (infile, outfile);
 infile.close();
outfile.close();
 return 0;
 }

void reverse (ifstream & infile, ofstream & outfile) {
 string s;
 stack<string> mystack;

 getline(infile, s); // try to read a line of text from the file
 while (!infile) { // while not end of file
  mystack.push(s);
  getline(infile, s); // try to read another line
  }
 while (! mystack.isEmpty() ) {
  s = mystack.pop();
  outfile << s << endl; // write s to the outfile
  }
 }

3 个答案:

答案 0 :(得分:2)

怎么样:

//open infile in and outfile out.
std::stack<std::string> lines;
std::string temp;
while(std::getline(in, temp)) lines.push(temp);
while(!lines.empty()) outfile << lines.pop() << std::endl;

我不确定你的问题到底是什么。

修改:分别将push_back()pop_back更改为push()pop()(因为这些是std::stack提供的内容)。

答案 1 :(得分:1)

摆脱!

while (infile) { // while not end of file

您可以使用std::stack代替"stack1.h"中的任何内容。

答案 2 :(得分:0)

检查这个,你可以直接存储它而不使用stack.I认为它应该工作。

int checkstatus(ifstream &in)
{
ios::iostate i;
i = in.rdstate();
if(i & ios::eofbit)
return 0;//cout << "EOF encountered\n";
else if(i & ios::failbit)
return 0;//cout<<"Non-Fatal I/O error\n";
else if(i & ios::badbit)
return 0;//cout<<"Fatal I/O error\n";

return 1;
}


int main()
{
    ifstream in;
    in.open("test.txt");
    char c;
    in.seekg(0,ios::end);
        while(checkstatus(in) != 0)
        {
            in.seekg(-1,ios::cur);
            in.get(c);
            in.seekg(-1,ios::cur);
            if(checkstatus(in) == 0)
            break;
            cout<<c;

        }
    return 0;
}