I am writing a program to manipulate a stack containing integers using push, pop, print, etc. The only thing I have left is to write a function called copy. Here is what I've tried so far:

void Stack::Copy(Stack otherStack)
		{

			otherStack.top = top;
							
			for (int ii = top-1; ii >= 0; ii--) 
                       {
				otherStack.Push(elements[ii]);

		       }
                }

and this:

void Stack::Copy(Stack otherStack)
		{

			otherStack.top = top;
							
			for (int ii = top-1; ii >= 0; ii--) {
				otherStack.elements[ii] = elements[ii];
		}
		
		}

Any help would be appreciated!

thanks

Recommended Answers

All 10 Replies

1. Use code tag with the language specifier:
[code=cpluplus] source

[/code]
2. We can't help you (mor precisely, we can't verify your solution) without class Stack definition. However I see that your Copy member signature is wrong. You never modify passed by value parameter. If you want to copy from *this to otherStack, use a reference to otherStack:

void Stack::Copy(Stack& otherStack);

3. Better try to overload Stack::operator=() and define copy constructor for this class. Essentially it's the same code as for Copy member.

On the other note, Would Elements or Top be accessible if they are private?

here is all I have so far:

Project.cpp:

//					 
//
//=================
#include "stdafx.h"
#include <iostream>
#include <string>
//===============

//================
#include "Stack.h"
//================

//==================
using namespace std;
//==================

//  ============
//  Enumerations
//  ===========================================
	enum menuSelections {Push, Pop, Initialize,
						 Print, Purge, Sum, Average, Roll, Copy};
//  ===================================

//  ===================
//  Function Prototypes
//  ==========================
	void GetAnswer( string& );
	void Finished( string, bool& );
    void Menu( menuSelections& );
	void ProcessCommandA( menuSelections,
				         Stack& );
	void ProcessCommandB( menuSelections,
						 Stack& );
//	==============================

//  ===========
    int main( )
    {
//	=====================
//	Variable Declarations
//	=============================
	menuSelections menuSelection;


    bool   finished = false;
	string userAnswer;
	char stackChoice;


    Stack stackA;
	Stack stackB;
//	====================

//	========================================
//	Welcome Banner and Instructions for User
//	=========================================================
	cout << "=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+" << endl;
	cout << "+                             +" << endl;
	cout << "= WELCOME TO THE STACK TESTER =" << endl;
	cout << "+                             +" << endl;
	cout << "=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=" << endl;
	cout << endl << endl;

	cout << "THIS PROGRAM ALLOWS THE USER TO CREATE" << endl;
	cout << "AND MANIPULATE A STACK WHOSE VALUES ARE" << endl;
	cout << "HELD BY A STATIC ARRAY." << endl;
	cout << "=+=+=+=+=+=+=+=+=+=+=+=" << endl;
	cout << endl << endl;
//	=====================

//		=========
//		User Loop
//		===================
		while ( !finished ) 
		{
			Menu( menuSelection );



			cout << "Which Stack?(a/b)" << endl;
			cin >> stackChoice;


			if (stackChoice == 'a')
				ProcessCommandA( menuSelection,
								stackA);
			else if (stackChoice == 'b')

			ProcessCommandB( menuSelection,
							stackB );
			else
			{
				cout << "Bad Choice, try again:" << endl;
			cin >> stackChoice;
			}


//			===========================
//			User loop termination code.
//			========================
			GetAnswer( userAnswer );
			Finished( userAnswer, finished );
//			=================================

		} // while loop
//		===============


	return 0;
}//End Function Main
//==================


//	==================
//	Function GetAnswer
//	==============================
	void GetAnswer( string& answer )
	{
	bool validAnswer = false;
		while ( !validAnswer ) 
		{
		    cout << "Would you like to modify one of the stacks again? (y or n)" 
			     << endl;
		    cin >> answer;

		    if (( answer.length() == 1 ) && 
			  (( answer[0] == 'y' ) || ( answer[0] == 'n' )))
				    validAnswer = true;
		
			else
				cout << "Invalide choice. Please enter (y or n)"
				     << endl;
		}			
	}//End Function GetAnswer
//	=========================

//  =================
//  Function Finished
//  =============================
	void Finished( string answer,
		           bool&  finished )
	{
		if (answer[0] == 'n')
			finished = true;
	}//End Function Finished
//	========================


//  =============
//  Function Menu
//  ==============================================
	void Menu( menuSelections& userMenuSelection )
	{
		int selectionNumber = 1;

		cout << "=+=+=+=+=+=+=+=+=+=+=+=+=+" << endl;
		cout << "MENU FOR TESTING THE STACK" << endl;
		cout << endl;
		cout << "1: Push" << endl;
		cout << "2: Pop" << endl;
		cout << "3: Initialize Stack" << endl;
		cout << "4: Print Stack" << endl;
		cout << "5: Purge Stack" << endl;
		cout << "6: Sum of Stack" << endl;
		cout << "7: Average of Stack" << endl;
		cout << "8: Roll Top Two Elements" << endl;
		cout << "9: Copy stack to other instance" << endl;

		cout << endl;

		cout << "What is your selection?" << endl;
        cin >> selectionNumber;

		switch ( selectionNumber )
		{
		    case 1: userMenuSelection = Push;
				break;
		    case 2: userMenuSelection = Pop;
				break;
		    case 3: userMenuSelection = Initialize;
				break;
		    case 4: userMenuSelection = Print;
				break;
		    case 5: userMenuSelection = Purge;
				break;
			case 6: userMenuSelection = Sum;
				break;
			case 7: userMenuSelection = Average;
				break;
			case 8: userMenuSelection = Roll;
				break;
			case 9: userMenuSelection = Copy;
				break;
		    default: 
			        cout << "Invalid selection." << endl;
			        cout << "The selection is being set to 4: Print." << endl;
			        userMenuSelection = Print;					
				break;
		}

	}//End Function Menu
//	====================


//  ========================
//  Function ProcessCommandA
//  ======================================================
	void ProcessCommandA( menuSelections userMenuSelection,
				         Stack& stackA )
	{
		Stack stackB;
		int integerValue;
		int sum;
		switch( userMenuSelection )
		{
		    case Push:
				     cout << "Enter a value to add to the list." << endl;
				     cin >> integerValue;
				 stackA.Push(integerValue);
				break;
			case Pop: stackA.Pop(integerValue);
				break;
			case Initialize: stackA.InitializeStack( );
				break;
		    case Print: stackA.PrintStack( );
				break;
		    case Purge: stackA.PurgeStack( );
				break;
			case Sum: stackA.SumOfElements( sum );
				break;
			case Average: stackA.Average( );
				break;
			case Roll: stackA.Roll( );
				break;
			case Copy: stackA.Copy(  stackB );
				break;
		    default: 
			        cout << "Invalid selection." << endl;
			        cout << "Print member-function invoked." << endl;
			        stackA.PrintStack();				
				break;
		}

	}//End Function ProcessCommandA
//	===============================


//  ========================
//  Function ProcessCommandA
//  ======================================================
	void ProcessCommandB( menuSelections userMenuSelection,
				         Stack& stackB )
	{
		Stack stackA;
		int integerValue;
		int sum;
		switch( userMenuSelection )
		{
		    case Push:
				     cout << "Enter a value to add to the list." << endl;
				     cin >> integerValue;
				 stackB.Push(integerValue);
				break;
			case Pop: stackB.Pop(integerValue);
				break;
			case Initialize: stackB.InitializeStack( );
				break;
		    case Print: stackB.PrintStack( );
				break;
		    case Purge: stackB.PurgeStack( );
				break;
			case Sum: stackB.SumOfElements( sum );
				break;
			case Average: stackB.Average( );
				break;
			case Roll: stackB.Roll( );
				break;
			case Copy: stackB.Copy(  stackA );
				break;
		    default: 
			        cout << "Invalid selection." << endl;
			        cout << "Print member-function invoked." << endl;
			        stackB.PrintStack();				
				break;
		}

	}//End Function ProcessCommandB
//	===============================

Stack.h:

//=======
//Stack.h
//=======
//    |
//  \ |	/
//   \|/
//	  V
//  ===========
   #pragma once
//  ===========

//  ===========
    class Stack
    {
//      =========
//      Constants
//		======================================
        const static int MAX_STACK_SIZE = 200;
		//      ======================================

//		=======
        public:
//		=======

//			============
//			Constructors
//			=============
	        Stack(void);
//			============

//			==========
//			Destructor
//			============
	       ~Stack(void);
//          ============

//          ================
//			Member Functions
//          ==========================
            void Stack::PurgeStack( );
            void Stack::InitializeStack( );
            void Stack::Pop( int& );
	        void Stack::PrintStack( );
            void Stack::Push( int );
            bool Stack::StackEmpty( );
            bool Stack::StackFull( );
			int Stack::SumOfElements(int& );
			void Stack::Average( );
			void Stack::Roll( );
			void Stack::Copy( Stack& );
//          =========================

//		========
	    private:
//		========

//          ================
//          Member variables
//          ========
	        int top;
	        int elements[MAX_STACK_SIZE];
//          =============================

    }; // Class Stack
//  =================

//===========
//End Stack.h
//===========

Stack.cpp:

//=========
//Stack.cpp
//=========
//    |
//  \ |	/
//   \|/
//	  V
//=================
#include "StdAfx.h"
#include <iostream>
#include <iomanip>
//=================

#include "Stack.h"
//================

//==================
using namespace std;
//==================

//  ============
//  Constructors
//  ============
        
//      ===================
//      Default Constructor
//		==================== 
        Stack::Stack( void )
        {
			PurgeStack();
        } //End Constructor
//		===================

//  ==========
//  Destructor
//	=====================
    Stack::~Stack( void )
    {

    } //End Destructor
//	==================

//  ================
//  Member-Functions
//  ================
        
//      ===================
//		Function PurgeStack
//      =========================
        void Stack::PurgeStack( )
        {
            for (int ii = 0; ii < MAX_STACK_SIZE; ii++)
			{
                elements[ii] = 0;
	        } 
	        top = 0;
        }//End Function PurgeStack
//      ==========================

//      ========================
//		Function InitializeStack
//		==============================
        void Stack::InitializeStack( )
        {
            top = 0;
        }//End Function InitializeStack
//      ===============================

//      ============
//		Function Pop
//      ===================================
        void Stack::Pop( int& poppedValue )
        {
			if (!StackEmpty()){
	        top--;
            poppedValue = elements[top];
			PrintStack();
		}
			else
			PrintStack();
        } // Member-Function Pop
//      ========================

//      ===================
//      Function PrintStack
//      =========================      
	    void Stack::PrintStack( )
        {
			cout << endl << endl;
            cout << "+ Top of Stack  +" << endl;
			cout << "=+=+=+=+=+=+=+=+=" << endl;
			cout << endl;
            if ( StackEmpty() )
                cout << "The stack is empty." << endl;
            else{
                for ( int ii = top - 1; ii >= 0; ii-- ){
                    cout << "At index[" << ii << "] = "
                         << elements[ii] << endl;
                } // for
            } // else
			cout << endl;
			cout << "=+=+=+=+=+=+=+=+=" << endl;
            cout << "+Bottom of Stack+" << endl << endl;
        }//End Function PrintStack
//      ==========================

//      =============
//		Function Push
//		===================================
        void Stack::Push( int pushedValue ) 
        {
            elements[top] = pushedValue;
            top++;
			PrintStack();
        }//End Function Push
//      =========================

//      ===================
//		Function StackEmpty
//      =========================
        bool Stack::StackEmpty( )
        {
            return (top == 0);
        }//End Function StackEmpty
//      ==========================

//      ==================
//		Function StackFull
//      ========================
        bool Stack::StackFull( )
        {
            return (top == MAX_STACK_SIZE);
        }//End Function StackFull
//      =========================

//      ======================
//		Function SumOfElements
//      ==================================
		int Stack::SumOfElements(int& sum)
		{
			sum = 0;
			for (int ii = 0; ii <= (top-1);ii++)
				sum = sum + elements[ii];
			cout << "Sum = " << sum << endl;
			return sum;
		}//End SumOfElements
//		====================

//      ================
//		Function Average
//      ======================
		void Stack::Average( )
		{
			cout << fixed << showpoint << setprecision(2);

			int sum;
			double result = 0;
			cout << endl;
			SumOfElements( sum );
			cout << endl;
			double total = sum;
			double divisor = top;

			if (sum == 0)
				cout << "Average = 0, the stack is empty" << endl << endl;
			else
			{
			result = total/ divisor;
			cout << "Average = " << result << endl << endl;
			}
		}

		void Stack::Roll( )
		{
			if (top == 0)
				cout << "Stack is empty, There are no elements to roll" << endl << endl;
			else if (top == 1)
				cout << "There is only one element in the stack, nothing to roll with" << endl << endl;
			else
			{
			int temp;
			temp = elements[top-1];
			elements[top-1] = elements[top-2];
			elements[top-2] = temp;
			PrintStack( );
			}
		}

		  void Stack::Copy( Stack& otherStack)
		{
			 otherStack.top = top;


			for ( int ii = top-1; ii >=0 ; ii--){

			otherStack.Push(elements[ii]);
			}
	

		
		}





//  ====================
//  End Member-Functions
//  =====================

//=============
//End Stack.cpp
//=============

I am writing a program to manipulate a stack containing integers using push, pop, print, etc. The only thing I have left is to write a function called copy. Here is what I've tried so far:

void Stack::Copy(Stack otherStack)
		{

			otherStack.top = top;
							
			for (int ii = top-1; ii >= 0; ii--) 
                       {
				otherStack.Push(elements[ii]);

		       }
                }

and this:

void Stack::Copy(Stack otherStack)
		{

			otherStack.top = top;
							
			for (int ii = top-1; ii >= 0; ii--) {
				otherStack.elements[ii] = elements[ii];
		}
		
		}

Any help would be appreciated!

thanks

Why are you copying the stack in reverse?
Though it doesnt matter :) in the second function
And Are you getting an error during compilation?

no errors, and I have tried both ways, I've tried every way even if it sounded crazy, I am stumped.

void Stack::Copy(Stack otherStack)
		{

			otherStack.top = top;
							
			for (int ii = top-1; ii >= 0; ii--) 
                       {
				otherStack.Push(elements[ii]);

		       }
                }

I found an error in your code

When you use push(element)
Why did you assign OtherStack.top=top;
That way you assign variables above the current stack size.

For example

Stack size =10;
so top =10;
when push(element );
is called.
then what we have is elements[top]=element //Which is actually 10;
Then 10++ is 11


Though my explaination is a little rough i hope you get the point

That was just the latest incarnation I've tried. I cannot figure out why either:
Push(otherStack.elements[ii]);
or
otherStack.Push(elements[ii]);
or
elements[ii] = otherStack.elements[ii];
or
otherStack.elements[ii] = elements[ii];

will not work...
am I missing something here?

void Stack::Copy( Stack& otherStack)
		{
			 
			for ( int ii = 0; ii <=top-1 ; ii++){

			otherStack.Push(elements[ii]);
			}
	

		
		}

I have tried your code. and it executed. The only mistake that you have made was that you have defined stack A while working with Stack B and vice versa locally. So all the info is gone after that function is executed.

//					 
//
//=================
#include "stdafx.h"
#include <iostream>
#include <string>
//===============

//================
#include "Stack.h"
//================

//==================
using namespace std;
//==================

//  ============
//  Enumerations
//  ===========================================
	enum menuSelections {Push, Pop, Initialize,
						 Print, Purge, Sum, Average, Roll, Copy};
//  ===================================

//  ===================
//  Function Prototypes
//  ==========================
	void GetAnswer( string& );
	void Finished( string, bool& );
    void Menu( menuSelections& );
	void ProcessCommandA( menuSelections,
				         Stack& );
	void ProcessCommandB( menuSelections,
						 Stack& );
//	==============================

//  ===========
    int main( )
    {
//	=====================
//	Variable Declarations
//	=============================
	menuSelections menuSelection;


    bool   finished = false;
	string userAnswer;
	char stackChoice;


    Stack stackA;
	Stack stackB;
//	====================

//	========================================
//	Welcome Banner and Instructions for User
//	=========================================================
	cout << "=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+" << endl;
	cout << "+                             +" << endl;
	cout << "= WELCOME TO THE STACK TESTER =" << endl;
	cout << "+                             +" << endl;
	cout << "=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=" << endl;
	cout << endl << endl;

	cout << "THIS PROGRAM ALLOWS THE USER TO CREATE" << endl;
	cout << "AND MANIPULATE A STACK WHOSE VALUES ARE" << endl;
	cout << "HELD BY A STATIC ARRAY." << endl;
	cout << "=+=+=+=+=+=+=+=+=+=+=+=" << endl;
	cout << endl << endl;
//	=====================

//		=========
//		User Loop
//		===================
		while ( !finished ) 
		{
			Menu( menuSelection );



			cout << "Which Stack?(a/b)" << endl;
			cin >> stackChoice;


			if (stackChoice == 'a')
				ProcessCommandA( menuSelection,
								stackA);
			else if (stackChoice == 'b')

			ProcessCommandB( menuSelection,
							stackB );
			else
			{
				cout << "Bad Choice, try again:" << endl;
			cin >> stackChoice;
			}


//			===========================
//			User loop termination code.
//			========================
			GetAnswer( userAnswer );
			Finished( userAnswer, finished );
//			=================================

		} // while loop
//		===============


	return 0;
}//End Function Main
//==================


//	==================
//	Function GetAnswer
//	==============================
	void GetAnswer( string& answer )
	{
	bool validAnswer = false;
		while ( !validAnswer ) 
		{
		    cout << "Would you like to modify one of the stacks again? (y or n)" 
			     << endl;
		    cin >> answer;

		    if (( answer.length() == 1 ) && 
			  (( answer[0] == 'y' ) || ( answer[0] == 'n' )))
				    validAnswer = true;
		
			else
				cout << "Invalide choice. Please enter (y or n)"
				     << endl;
		}			
	}//End Function GetAnswer
//	=========================

//  =================
//  Function Finished
//  =============================
	void Finished( string answer,
		           bool&  finished )
	{
		if (answer[0] == 'n')
			finished = true;
	}//End Function Finished
//	========================


//  =============
//  Function Menu
//  ==============================================
	void Menu( menuSelections& userMenuSelection )
	{
		int selectionNumber = 1;

		cout << "=+=+=+=+=+=+=+=+=+=+=+=+=+" << endl;
		cout << "MENU FOR TESTING THE STACK" << endl;
		cout << endl;
		cout << "1: Push" << endl;
		cout << "2: Pop" << endl;
		cout << "3: Initialize Stack" << endl;
		cout << "4: Print Stack" << endl;
		cout << "5: Purge Stack" << endl;
		cout << "6: Sum of Stack" << endl;
		cout << "7: Average of Stack" << endl;
		cout << "8: Roll Top Two Elements" << endl;
		cout << "9: Copy stack to other instance" << endl;

		cout << endl;

		cout << "What is your selection?" << endl;
        cin >> selectionNumber;

		switch ( selectionNumber )
		{
		    case 1: userMenuSelection = Push;
				break;
		    case 2: userMenuSelection = Pop;
				break;
		    case 3: userMenuSelection = Initialize;
				break;
		    case 4: userMenuSelection = Print;
				break;
		    case 5: userMenuSelection = Purge;
				break;
			case 6: userMenuSelection = Sum;
				break;
			case 7: userMenuSelection = Average;
				break;
			case 8: userMenuSelection = Roll;
				break;
			case 9: userMenuSelection = Copy;
				break;
		    default: 
			        cout << "Invalid selection." << endl;
			        cout << "The selection is being set to 4: Print." << endl;
			        userMenuSelection = Print;					
				break;
		}

	}//End Function Menu
//	====================


//  ========================
//  Function ProcessCommandA
//  ======================================================
	void ProcessCommandA( menuSelections userMenuSelection,
				         Stack& stackA )
	{
		Stack stackB;
		int integerValue;
		int sum;
		switch( userMenuSelection )
		{
		    case Push:
				     cout << "Enter a value to add to the list." << endl;
				     cin >> integerValue;
				 stackA.Push(integerValue);
				break;
			case Pop: stackA.Pop(integerValue);
				break;
			case Initialize: stackA.InitializeStack( );
				break;
		    case Print: stackA.PrintStack( );
				break;
		    case Purge: stackA.PurgeStack( );
				break;
			case Sum: stackA.SumOfElements( sum );
				break;
			case Average: stackA.Average( );
				break;
			case Roll: stackA.Roll( );
				break;
			case Copy: stackA.Copy(  stackB );
				break;
		    default: 
			        cout << "Invalid selection." << endl;
			        cout << "Print member-function invoked." << endl;
			        stackA.PrintStack();				
				break;
		}

	}//End Function ProcessCommandA
//	===============================


//  ========================
//  Function ProcessCommandA
//  ======================================================
	void ProcessCommandB( menuSelections userMenuSelection,
				         Stack& stackB )
	{
		Stack stackA;
		int integerValue;
		int sum;
		switch( userMenuSelection )
		{
		    case Push:
				     cout << "Enter a value to add to the list." << endl;
				     cin >> integerValue;
				 stackB.Push(integerValue);
				break;
			case Pop: stackB.Pop(integerValue);
				break;
			case Initialize: stackB.InitializeStack( );
				break;
		    case Print: stackB.PrintStack( );
				break;
		    case Purge: stackB.PurgeStack( );
				break;
			case Sum: stackB.SumOfElements( sum );
				break;
			case Average: stackB.Average( );
				break;
			case Roll: stackB.Roll( );
				break;
			case Copy: stackB.Copy(  stackA );
				break;
		    default: 
			        cout << "Invalid selection." << endl;
			        cout << "Print member-function invoked." << endl;
			        stackB.PrintStack();				
				break;
		}

	}//End Function ProcessCommandB
//	===============================

I think you should remove those declarations over there and declare them globally and the program will run fine.

I see where thats a problem, but when I remove them I get these errors:

Error 2 error C2065: 'stackA' : undeclared identifier
Error 1 error C2065: 'stackB' : undeclared identifier


Thanks

Sorry I didn't see 'declare globally' My mistake

thanks so much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.