// // Program to test stack class. // (This file is meant to be #include'd by another file that // uses a "typedef XXXX stacktype" to set the type of items // in the stack.) // // Program is driven by command input: // P x -- push x onto stack. // p -- pop top element from stack. // t -- print top element of stack. // s -- print size of stack and whether empty. // c -- test copy constructor by creating a copy of the // current stack and (destructively) printing the // copy. // a -- test assignment by creating stack with one element, // using '=' to replace it with current stack, and // (destructively) printing the new stack. // end-of-file to quit // Lines beginning "#" are ignored. // #include #include #include "stack.h" void printAndDestroy(stack & s1) { while (!s1.empty()) { cout << s1.top() << endl; s1.pop(); } return; } int main() { stack s1; char cmd; char prompt[] = "Command? "; cerr << prompt; while (cin >> cmd) { if (cmd == '#') cin.ignore(10000,'\n'); if (cmd == 'P') { stacktype elem; cin >> elem; s1.push(elem); } else if (cmd == 'p') s1.pop(); else if (cmd == 't') cout << "top element = " << s1.top() << endl; else if (cmd == 's') { cout << "size of stack = " << s1.size() << endl; if (s1.empty()) cout << "stack is empty\n"; else cout << "stack is not empty\n"; } else if (cmd == 'c') { stack s1copy(s1); cout << "copy of stack, made with copy constructor:\n"; printAndDestroy(s1copy); } else if (cmd == 'a') { stack s1copy; s1copy.push(s1.top()); s1copy = s1; cout << "copy of stack, made with assignment:\n"; printAndDestroy(s1copy); } cerr << prompt; } cerr << endl; cout << "\nThat's all, folks!\n"; return EXIT_SUCCESS; }