//-----------------------------------------------------------------------
// mystack.cc
//-----------------------------------------------------------------------
// Written by Charles A. Cusack, August 1999
//
// This is a simple program that reads informtation from an input file,
// and performs one of several tasks.
// Each entry in the file is either 'u #', 'o', or 'p'.
// If the entry is 'u #', the number '#' is inserted onto the stack
// If the entry is 'o', the top of the stack is deleted
// If the entry is 'p', the remaining elements in the stack are printed
// and the program terminates.
// This program uses the class 'Stack' defined in the files
// stack.h and stack.cc
//-----------------------------------------------------------------------
#include <fstream>
#include <iostream>
#include "stack.h" // Include the stack class header.
using namespace std;
//-----------------------------------------------------------------------
int main(int argc, char *argv[]) {
if(argc!=2) { // Check for correct number of arguments.
cout<<"USAGE: "<<argv[0]<<" filename\n";
exit(1);
}
ifstream infile(argv[1]);
Stack L(100); // The stack which we will store stuff on
char operation=' '; // The operation to be performed
int value; // The item inserted/removed from the stack
while(operation!='p') { // Continue until the termination condition
infile>>operation; // Read until non-whitespace character is read
while(operation==' ' || operation=='\n')
infile>>operation;
if(operation=='u') { // Read and push the next integer
infile>> value; // Read in the integer to push
// Push the value. If there is an error quit
if (!L.Push(value)) {
cout<<"The stack is full, and I was asked to push\n";
cout<<"an element. I can't do that, so I am quitting.\n\n";
exit(3);
}
}
else if(operation=='o') { // Pop the stack if possible
if( !L.Empty() ) { // Check that the stack is not empty
value=L.Pop(); // Pop the stack
}
else { // If the stack is empty, quit
cout<<"The stack is empty, and I was asked to pop\n";
cout<<"an element. I can't do that, so I am quitting.\n\n";
exit(4);
}
}
else if(operation=='p') { // Print and quit
while( !L.Empty() ) { // Pop and print each element
cout<<L.Pop()<<" ";
}
cout<<"\n"; }
else { // Something is wrong with the input file, so quit
cout<<"I was asked to do some unknown task.\n";
cout<<"Since I don't know what to do, I am quitting.\n\n";
exit(4);
}
}
infile.close(); // Close the input file
return 0;
}
//-----------------------------------------------------------------------