Thread: stack question
View Single Post
Old May 8th, 2006, 7:54 PM   #10
The Dark
Expert Programmer
 
Join Date: Jun 2005
Posts: 825
Rep Power: 4 The Dark is on a distinguished road
To make it shorter, put the repeated code into a template function:
template <class stackType, int MaxStack> void driverLoop()
{
  Stack<stackType, MaxStack>* stackClassDriver = new Stack<stackType, MaxStack>;
	while (1)
	{
		stackType stackItem;
		int stackOperation;

		cout<<"1:\tpush\t2:\tpop"<<endl;
		cout<<"3:\tprint\t4:\tmain menu"<<endl;
		cout<<"(choose 1-4)\n\n"<<endl;
		cin>>stackOperation;

		if(stackOperation ==1)
		{    
			cout << "Enter stackItem to push: ";
			cin >> stackItem;

			stackClassDriver->push(stackItem);
		}

		else if(stackOperation == 2)
		{
			stackClassDriver->pop();
		}

		else if(stackOperation == 3)
		{
			stackClassDriver->print();
		}

		else if(stackOperation == 4)
		{
			delete stackClassDriver;
			stackClassDriver = 0;
			break;
		}

		else
		{
			cout<<"invalid selection...\n\n"<<endl;
			continue;
		}
	}//end while
}
Then you can call it in your if statements like this:
		if (mainMenuChoice == 1)//begin int stack stackClassDriver
		{
                   driverLoop<int, MaxStack>();
		}//end int stack stackClassDriver

		else if (mainMenuChoice == 2)//begin long stack stackClassDriver
		{
                  driverLoop<long, MaxStack>();
		}//end long stack stackClassDriver
The Dark is offline   Reply With Quote