请帮助我是 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
}
}
最佳答案
怎么样:
//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
提供的)。
关于C++如何读取文本文件并反转行以便从下到上读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2308505/