------------------------------------------------------------------------------
MC logo
Generalized Stack Driver
[^] Code Examples
------------------------------------------------------------------------------
<<Generalized Stack Implementation genstackuse.cc Ugly Shapes>>
#include <iostream>
#include <string>
#include "genstack.h"

// Simple generalize stack user calss.

// Integer type stack elements.
class Int_Stack_Elt: public Stack_Elt
{
        int n;
 public:
        Int_Stack_Elt(int i) { n = i; }
        int get() const { return n; }
        virtual void print(ostream &strm) const { strm << n; }
};

// String type stack elements.
class String_Stack_Elt: public Stack_Elt
{
        string s;
 public:
        String_Stack_Elt(string as) { s = as; }
        String_Stack_Elt(const char *cs) { s = cs; }
        string get() const { return s; }
        virtual void print(ostream &strm) const { strm << s; }
};

// Simple test driver.
main()
{
        Stack s;                // One ordinary stacks.
        SelfCleaningStack q,t;  // Two advanced models.
        int inint;              // Input integer.
        string instr;           // Input string.

        // Read integers, then strings.
        while(cin >> inint) {
                s.push(new Int_Stack_Elt(inint));
                t.push(new Int_Stack_Elt(inint));
        }
        cin.clear();
        while(cin >> instr) {
                q.push(new String_Stack_Elt(instr));
                t.push(new String_Stack_Elt(instr));
                t.push(new Int_Stack_Elt(instr.length()));
        }
        // Print 'em all.
        cout << s << endl;
        cout << q << endl;
        cout << t << endl;

        // Print the integers.
        while(!s.empty())
        {
                Int_Stack_Elt *t = (Int_Stack_Elt *)s.pop();
                cout << t->get() << " ";
                delete t;
        }
        cout << endl;

        // Print the general stack.
        while(!t.empty())
        {
                Stack_Elt *e = t.pop();
                e->print(cout);
                cout << " ";
                delete e;
        }
        cout << endl;

        // Let the self-cleaning stack q clear up it's own nodes.
}

This class uses the generalized stack. It creates two classes derived from Stack_Elt which it places on the stack.

One other thing we haven't seen before is the cin.clear(). The two loops work by reading in integers until the read fails, then reading strings. When the read fails, cin goes into the bad state, and won't read again until we clear it.
<<Generalized Stack Implementation Ugly Shapes>>