Question: C++ Modify the Stack class to include appropriate error messages if invalid conditions occurfor example, trying to pop an item when the stack is empty.

C++ Modify the Stack class to include appropriate error messages if invalid conditions occurfor example, trying to pop an item when the stack is empty.

A SIMPLE STACK CLASS

main.cpp

/*******************************

* Week 2 lesson: *

* a simple Stack class *

*******************************/

#include

#include "stack.h"

using namespace std;

int main()

{

Stack s;

cout << "Insertion of 10 characters in s" << endl;

for (int i = 0; i < s.getSize(); i++)

{

char x = 32 + rand()%95;

cout << x << endl;

s.push(x);

}

cout << endl

<< "Displaying and deleting elements from s" << endl;

while(!s.isEmpty())

{

cout << "Item at the top: " << s.peek() << endl;

s.pop();

}

return 0;

}

Stack.cpp

/*******************************

* Week 2 lesson: *

* a simple Stack class *

*******************************/

#include "Stack.h"

/*

* Constructor. Initializes the stack.

*/

Stack::Stack()

{

top = 0;

}

/*

* Determines whether the stack is empty.

*

* Returns true if the stack is empty, false otherwise.

*/

bool Stack::isEmpty()

{

return top == 0;

}

/*

* Adds an element to the top of the stack.

*

* x: element to be added to the stack.

*/

void Stack::push(char x)

{

list[top] = x;

top++;

}

/*

* Removes the element at the top of the stack.

*/

void Stack::pop()

{

top--;

}

/*

* Returns the element at the top of the stack. Does not remove it.

*/

char Stack::peek()

{

return list[top-1];

}

/*

* Returns the size of the stack.

*/

int Stack::getSize()

{

return SIZE;

}

Stack.h

/*******************************

* Week 2 lesson: *

* a simple Stack class *

*******************************/

/*

* Class implementing a Stack ADT.

*/

class Stack

{

public:

Stack();

bool isEmpty();

void push(char);

void pop();

char peek();

int getSize();

private:

static const int SIZE = 10; //size of the queue array

char list[SIZE]; //array to store the stack items

int top; //amount of elements in the array

};

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!