Lab 14: Experiment 1

Working with a stack

The Problem

What happens if we input a bunch of words, push them all onto a stack, and then, as we pop them off, display them?

The Prediction

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   theStack
 the file name  string  varying  inFileName 
 the keyboard  istream  varying  cin
 the input stream  ifstream  varying  inStream
 a word  string  varying  word
 the screen  ostream  varying  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() constructor   stack
 push a word onto the stack   yes  push()  stack
 test if stack is empty  yes  empty()  stack
 get top value from stack  yes  top()  stack
 pop 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:

  1. Create a new, empty stack theStack.
  2. Display a prompt for the input file name.
  3. Read inFileName.
  4. Open inStream (using inFileName) and test that it opened properly.
  5. Loop:
    1. Read word from inStream.
    2. If inStream is at the end-of-file, terminate the loop.
    3. Push word onto theStack.
  6. Close inStream.
  7. While theStack is not empty:
    1. Display the top of theStack on the screen (followed by some whitespace).
    2. Pop the top value from theStack.

Write the program, compile it, and execute it.

The Analysis

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?

Back to the Lab Exercise |  Forward to Experiment #2

Report errors to Larry Nyhoff (