首页 > 解决方案 > Can't get a top element of the filled stack

问题描述

I stuck with stack) In this code I'n filling few stacks and later trying to get a date from them. But with char stack I got a problem-error.

Declared stack in the header

stack<int> numbers;
stack<char> operators;

Input method

void Notation::InptWriter() {
    notationPtr = new char[SIZE];
    cout << "Enter expression: ";
    cin.getline(notationPtr, SIZE);
}

This method for filling up the stacks(1 for integers,1 for char)

void Notation::Convert(char *ptr, int *store) {
    int x = 0;
    static string y = "";

    for (int i = 0; i < strlen(ptr); i++) {
        if (isdigit(*(ptr + i))) {  //for numbers greater that 9
            y += *(ptr + i);
        } else { // if inline char isNaN push char to Operator stack, then convert 'y' to int and push to number stack
            operators.push(*(ptr + i));//push value to the stack
            if (y != "") {
                x = stoi(y);
                numbers.push(x);
                y = "";
            }
        }
        if (!operators.empty()) {
            cout << "op: " << operators.top();
        }
        if (!numbers.empty()) {
            cout << "__Num: " << numbers.top();
        }
        cout << "----" << *(ptr + i) << "---" << y << endl;
    }
}

Here I try to initialize the variable with the same data type from the stack and get an error during runtime

 void Notation::StackWorking(stack<int> nums, stack<char> opers) {
    char op;
    int num;
cout<<operators.top()<<" "<<numbers.top();
while (!opers.empty() && !nums.empty()){
        cout<<"in";
        op = operators.top();//Problem over there
        operators.pop(); 
        num = numbers.top();
        numbers.pop();
        cout << op << " " << num << endl;
    }

Thank you!

I commended a lines where I look on top of the stack and everything start to work...

if (!operators.empty()) {
          //  cout << "op: " << operators.top();
        }
        if (!numbers.empty()) {
          //  cout << "__Num: " << numbers.top();

but i still don't know why...

标签: c++stack

解决方案


It looks like you are using the wrong variable, In the while you you test opers ans nums

while (!opers.empty() && !nums.empty()){

where as in the loop you use operators and numbers

    op = operators.top();//Problem over there
    operators.pop(); 
    num = numbers.top();
    numbers.pop();

see working example here


推荐阅读