c ++“未在此范围内声明”错误

时间:2015-12-07 00:35:05

标签: c++ loops scope undefined

我一直收到一个错误,告诉我我没有在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();
}

1 个答案:

答案 0 :(得分:1)

所以缓冲区是一个堆栈。堆栈什么? stack<int> buffer可以工作,或者stack<char> buffer,或者你需要的任何东西。

我无法分辨你需要什么。我注意到你正在推theFile,这没有意义。这可能有意义:

while( theFile.eof() == false ) 
{
    theFile >> something;
    if (! theFile) break; //if we reached eof or had other problems, just quit
    buffer.push(something);
}

取决于您要对空白做什么,somethingchar, char*还是string