-3

I keep getting an error telling me that I am not defining buffer in the scope under the if(!buffer.empty) loop.

Does anyone have any advice on what I should do and what I'm doing wrong?

#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();
}
juanchopanza
  • 210,243
  • 27
  • 363
  • 452
  • 2
    `std::stack` is a class template. See http://en.cppreference.com/w/cpp/container/stack. – juanchopanza Dec 07 '15 at 00:38
  • `std::stack` is a template, it needs parameters. More importantly why are you trying to push a `std::ifstream` to the stack? Why even use a stack in the first place? – user657267 Dec 07 '15 at 00:38
  • that part of the code was given by my professor already. I have to incorporate a stack or recursion to get the file to read what's in it, but backwards. – Nicholas DeTore Dec 07 '15 at 00:42

1 Answers1

1

So buffer's a stack. Stack of what? stack<int> buffer would work, or stack<char> buffer, or whatever it is you need a stack of.

I couldn't tell what you needed a stack of. I noted that you were pushing theFile, which doesn't make sense. This might make sense:

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

depending on what you want to do with whitespace, if something is char, char*, or string.

Topological Sort
  • 2,427
  • 19
  • 39
  • http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – juanchopanza Dec 07 '15 at 01:01
  • juanchopanza makes a good point: neither the original code nor my fix checks to see that nothing went wrong with reading in the `something`. I'll edit the post appropriately. – Topological Sort Dec 07 '15 at 03:23