Source of stack04.cpp


  1: //stack04.cpp

  3: #include <iostream>
  4: #include <stack>
  5: using namespace std;

  7: int main()
  8: {
  9:     cout << "\nThis program illustrates how *not* to access the "
 10:         "components of a stack.";
 11:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 13:     stack<char> s;
 14:     s.push('A');
 15:     s.push('B');
 16:     s.push('C');
 17:     s.push('D');

 19:     cout << "\nThe stack s contains " << s.size() << " values.";
 20:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 22:     cout << "\nNow we attempt to display the values in the stack "
 23:         "using a for-loop and\nchecking the size of the stack to "
 24:         "determine when to stop.";
 25:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 27:     cout << "\nHere they are, in \"LIFO\" order:\n";
 28:     for (stack<int>::size_type i=1; i<=s.size(); i++) //Whoops!
 29:     {
 30:         cout << "Popping: ";
 31:         cout << s.top() << "\n";
 32:         s.pop();
 33:     }
 34:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 35: }