This class is a stack and I'm trying to get the user to call functions related to the stack. However, no changes seem to be made, since when calling the display function, my entire stack is filled with zeros. This is after pushing values onto the stack.
#include <iostream>
using namespace std;
class Stack {
public:
int array[5];
int top;
Stack() {
top = -1;
for (int i = 0; i < 5; ++i) {
array[i] = 0;
}
}
bool isEmpty() {
if (top == -1) {
return true;
}
return false; }
bool isFull() {
if (top == 4) {
return true;
}
return false;
}
void push(int val) {
if (isFull()) {
cout <<"stack overflow" << endl;
}
else {
top++;
array[top] == val;
}
}
int pop() {
if (isEmpty()) {
cout << "stack underflow" << endl;
}
else {
int val = array[top];
array[top] = 0;
top--;
return val;
}
}
int count() {
return(top + 1);
}
int peek(int pos) {
if (isEmpty()) {
cout << "stack underflow";
return 0;
}
else {
return array[pos];
}
}
void change(int pos, int val) {
array[pos] = val;
}
void display() {
for (int i = 4; i >= 0; --i) {
cout << array[i];
}
}
};
int main() {
Stack stack;
int option, position, value;
do
{
cout << "What operation do you want to perform? Select Option number. Enter 0 to exit." << endl;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. isEmpty()"<< endl;
cout << "4. isFull()"<< endl;
cout << "5. peek()"<< endl;
cout << "6. count()"<< endl;
cout << "7. change()"<< endl;
cout << "8. display()"<< endl;
cout << "9. Clear Screen"<< endl<< endl;
cin >> option;
switch(option) {
case 1:
cout << "Enter item to push onto stack: " << endl;
cin>>value;
stack.push(value);
break;
case 2:
cout << "Popping from stack: " << stack.pop() << endl;
break;
case 3:
if (stack.isEmpty()) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
break;
case 4:
if (stack.isFull()) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
break;
case 5:
cout << "Enter position to peek" << endl;
cin >> position;
cout << stack.peek(position) << endl;
break;
case 6:
cout << stack.count() << endl;
break;
case 7:
cout << "Enter position followed by value: " << endl;
cin >> position >> value;
cout << "Position changed" << endl;
break;
case 8:
stack.display();
break;
case 9:
system("cls");
break;
}
}
while (option != 0);
return 0;
}
For example the user would press 1 to call push() and push some input value. Then, they'd enter 8 to call display and it should show that input value in the stack, but prints 00000