/* Filename: templat3.cpp Programmer: Br. David Carlson Date: June 28, 1998 Last Revised: December 23, 2001 This program prompts the user to enter a sequence of integers and prints prints them in reverse order. Then it prompts the user to enter a sequence of characters and prints them in reverse order. A template- based array implementation of a stack is used. Tested with: Microsoft Visual C++ 2019 */ #include using namespace std; const int StackMax = 200; // our stacks can only hold this many items template class ArrStackClass { public: ArrStackClass(void); bool Empty(void) const; void Push(const T & Item); void Pop(T & Item); private: int Top; T Info[StackMax]; }; /* Given: Nothing. Task: This is a constructor. It creates and initializes a new stack to empty. Return: Nothing other than the newly created object. */ template ArrStackClass::ArrStackClass(void) { Top = -1; } /* Given: Nothing (other than the implicit ArrStackClass object). Task: To check whether this object is empty. Return: true if it is empty, false otherwise. */ template bool ArrStackClass::Empty(void) const { if (Top < 0) return true; else return false; } /* Given: Item A data item. Task: To push item onto the stack (the implicit object). Return: Nothing directly, but the implicit object is modified. */ template void ArrStackClass::Push(const T & Item) { Top++; if (Top == StackMax) { cerr << "Error: no room to push an item onto the stack" << endl; exit(1); } else Info[Top] = Item; // assumes = works for type T } /* Given: Nothing. Task: To pop the top item from the stack (the implicit object). Return: Item The item popped from the stack. */ template void ArrStackClass::Pop(T & Item) { if (Top < 0) { cerr << "Error: cannot pop an item from an empty stack" << endl; exit(1); } else { Item = Info[Top]; // assumes that = works for type T Top--; } } int main(void) { ArrStackClass IntStack; ArrStackClass CharStack; int Number; char Ch; cout << "Enter an integer (0 to quit): "; cin >> Number; while (Number != 0) { IntStack.Push(Number); cout << "Enter another integer (0 to quit): "; cin >> Number; } if (IntStack.Empty()) cout << endl << endl << "Stack is empty" << endl; else { cout << endl << endl << "Numbers in reverse order are:" << endl; while (! IntStack.Empty()) { IntStack.Pop(Number); cout << Number << endl; } } cin.clear(); cout << endl << "Enter a character (q to quit): "; cin >> Ch; while (Ch != 'q') { CharStack.Push(Ch); cout << "Enter another character (q to quit): "; cin >> Ch; } if (CharStack.Empty()) cout << endl << endl << "Stack is empty" << endl; else { cout << endl << endl << "Characters in reverse order are:" << endl; while (! CharStack.Empty()) { CharStack.Pop(Ch); cout << Ch << endl; } } return 0; }