【发布时间】:2015-12-07 00:35:04
【问题描述】:
我不断收到错误消息,告诉我我没有在 if(!buffer.empty) 循环下的范围内定义缓冲区。
有人对我应该做什么以及我做错了什么有任何建议吗?
#include <fstream> // this is to import the ifstream and ofstream objects
#include <iostream> // this is to import the cin and cout objects
#include <stack>
using namespace std;
// precondition: theFile refers to a stream that has been opened already
// postcondition: the contents of the file have been read and output to the console
void read_file( ifstream& theFile ) {
stack buffer; // this string will read in the buffer from the file
//while there are still things in the file to read in, read it in and output to console.
while( theFile.eof() == false ) {
buffer.push(theFile);
//cout << buffer << endl; // print the string and a newline
}
if( !buffer.empty() ) {
cout << buffer.top() << endl;
buffer.pop();
}else{
cout << "uh oh!" << endl;
}
}
int main() {
ifstream theInputFile;
theInputFile.open("input.txt"); // Open the file with the name "inputFile.txt".
// pass the file stream into the read_file() function.
read_file( theInputFile );
theInputFile.close();
}
【问题讨论】:
-
std::stack是一个类模板。见en.cppreference.com/w/cpp/container/stack。 -
std::stack是一个模板,它需要参数。更重要的是,您为什么要尝试将std::ifstream推入堆栈?为什么首先要使用堆栈? -
我的教授已经给出了部分代码。我必须合并一个堆栈或递归才能让文件读取其中的内容,但要向后读取。