stackWhat happens if we input a bunch of words, push them all onto a stack, and then, as we pop them off, display them?
So what will happen to the words when they're output? Try this on your own first:
Question #14.1.1: The words "Madam I'm Adam" were pushed one after the other onto a stack and then they were printed as they were popped from the stack. What would be printed?
Question #14.1.2: Now predict what will happen in general to any sequence of words.
The behavior of the program you are to write is as follows:
The program will create a new empty stack. It will prompt for and read in a file name from the keyboard and then will open that file for input. Words are read from the file and each is pushed onto the stack .When the end-of-file is reached, the file is closed. Words are then popped from the stack and displayed on the screen (or if you prefer, written to an output file) until the stack is empty.
The objects for this program are quite straightforward:
Description Type Kind Name the stack of words stack<string>varying theStackthe file name stringvarying inFileNamethe keyboard istreamvarying cinthe input stream ifstreamvarying inStreama word stringvarying wordthe screen ostreamvarying cout
The operations are fairly straightforward as well. The following list omits the file operations, but you can look them up from previous labs.
Description Predefined? Name Library create a new stack yes stack()constructorstackpush a word onto the stack yes push()stacktest if stack is empty yes empty()stackget top value from stack yes top()stackpop top value from stack yes pop()stack
Declaring a stack is like declaring a vector or
list. Use the same syntax, but use "stack" for the container. The other operations will be
methods invoked on theStack.
So we end up with this algorithm:
theStack.inFileName.inStream (using inFileName) and test
that it opened properly.word from inStream.inStream is at the end-of-file, terminate the
loop.word onto theStack.inStream.theStack is not empty:
theStack on the screen (followed by
some whitespace).theStack.Write the program, compile it, and execute it.
Compare your prediction with the actual outcome.
Question #14.1.3: How closely did your prediction match the actual outcome?
Question #14.1.4: How does LIFO explain the behavior you see from your program?