dimanche 28 février 2021

Value of variable changes automatically in C++

I am coding a simple stack program for the students. the code is as below:

/**
 * This is a menu driven program to use stack
 * */

#include <iostream>

using namespace std;

const int stack_size = 10;
class Stack
{
private:
    /* data */
    int top;
    int data[stack_size - 1];

public:
    Stack()
    {
        top = -1;
    }
    ~Stack() {}

    void push(int x)
    {
        if (top == stack_size)
        {
            cout << "Error: Stack overflow..." << endl;
        }
        else
        {
            data[++top] = x;
            cout << "Item " << x << " pushed successfully..." << endl;
        }
    }

    void pop()
    {
        if (top == -1)
        {
            cout << "Error: Stack underflow..." << endl;
        }
        else
        {
            cout << "Item poped is: " << data[top--] << endl;
        }
    }
    void display()
    {
        cout << "Items in the stack" << endl;
        cout << "------------------" << endl;
        if (top == -1)
        {
            cout << "Stack is empty..." << endl;
        }
        else
        {
            for (int i = top; i >= 0; i--)
            {
                cout << data[i] << endl;
                ;
            }
        }
    }
};

int main()
{
    Stack s;
    char choice;
    int loop = 1, x;
    while (loop == 1)
    {
        cout << "Menu" << endl;
        cout << "1. Push" << endl;
        cout << "2. Pop" << endl;
        cout << "3. Display" << endl;
        cout << "4. Exit" << endl;
        cout << "Enter your choice: ";
        cin >> choice;
        switch (choice)
        {
        case '1':
            //push
            cout << "Enter value to push: ";
            cin >> x;
            s.push(x);
            break;
        case '2':
            //pop
            s.pop();
            break;
        case '3':
            //display
            s.display();
            break;
        case '4':
            //exit
            loop = 0;
            break;
        default:
            //invalid
            cout << "Error: Invalid Selection..." << endl;
            break;
        }
        //fflush(stdin);
    }
}

the problem is when I push 10 Items continuously, then after the 10th element, the value of the loop variable changes automatically. e.g. If I input 10 at the 10th iteration, after the push operation, the value of the loop becomes 10, if I input 11 at the 10th iteration, the value of loop becomes 11 and the while loop breaks. Please someone help me to figure out why this is happening.

Tools using vscode with mingw-64 and C/C++ extension pack and code runner extension.

Aucun commentaire:

Enregistrer un commentaire