C ++:我的堆栈顶部发生了什么?

时间:2018-02-20 05:38:35

标签: c++ stack std

我正在进行一项任务,我必须通过使用两个堆栈(一个用于保存值,一个用于保存运算符)来计算可能具有比较运算符<=>=的算术表达式。 )。

例如,输入1 + 2 - 3 * 4/5,程序应输出0.6。

但是,每当我在操作后将值推回valueStack时,堆栈顶部的值似乎会在退出doOp()方法后消失或变为垃圾值。我一直试图追踪和调试,但我仍然不知道为什么会这样。任何帮助或正确方向上的一点都会非常感激。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <stack>
#include <cstring>

using namespace std;

stack<char*> operatorStack;
stack<char*> valueStack;
string input;

void repeatOps(char refOp);
void doOp();
int prec(char refOp);

int main(){
    cout << "Enter expression to be evaluated: ";
    getline(cin, input);

    //Parse the string and perform EvalExp() Algorithm
    char *cString = strdup(input.c_str());
    char *token = strtok(cString, " ");
    while(token !=NULL){
        if(isdigit(token[0])){
            valueStack.push(token);
        }
        else{
            repeatOps(*token);
            operatorStack.push(token);
        }   
            token = strtok(NULL, " ");
    }
    repeatOps('$');
    //print out answer
    cout << valueStack.top() << endl;
}

void repeatOps(char refOp){
    while(valueStack.size() > 1 && prec(refOp) <= prec(*operatorStack.top())){
        //debug print statements REMOVE LATER 
        cout << "Printing top of stack in repeatOps before doOp():  " << valueStack.top() << endl;
        doOp();
    }
}

//return precedence of operator
int prec(char refOp){
    if(refOp == '*' || refOp == '/'){
        return 2;
    }
    else if(refOp == '+' || refOp == '-'){
        return 1;
    }
    //Use $ as a special "end of input" token with lowest precedence
    else if(refOp == '$'){
        return -1;
    }
    // if not any of the operators above, it's comparison operator return 0
    else{
        return 0;
    }
}

void doOp(){
    int x = atoi(valueStack.top());
    valueStack.pop(); 
    int y = atoi(valueStack.top());
    valueStack.pop();
    char * op = operatorStack.top();
    operatorStack.pop();

    double doubleReturnValue;
    bool booleanReturnValue;

    //If it's a comparison operator, push true or false and exit function
    if(strncmp(op, "<=", 2) == 0 || strncmp(op, ">=", 2) == 0){
        char trueResult[] = "true";
        char falseResult[] = "false";
        if(strncmp(op, "<=",2)){
            booleanReturnValue = y <= x;
        }
        else{
            booleanReturnValue = y >= x;
        }

        if(booleanReturnValue){
            valueStack.push(trueResult);
        }
        else{
            valueStack.push(falseResult);
        }
        return;
    }

    //Evaluate arithmetic
    if(*op == '+'){
        doubleReturnValue = y + x;
    }
    else if(*op == '-'){
        doubleReturnValue = y - x;
    }

    else if(*op == '*'){
        doubleReturnValue = y * x;
    }

    else if(*op == '/'){
        doubleReturnValue = y / x;
    }
    //convert the result of the operation to char * for the stack
    char returnChar[10];
    sprintf(returnChar, "%.3f", doubleReturnValue);
    //Debug print statements REMOVE LATER
    cout << "Printing return value in doOp() as char array " << returnChar << endl;
    valueStack.push(returnChar);
    cout << "Printing out top of stack after pushing in doOp(): " << valueStack.top() << endl << endl;
}

2 个答案:

答案 0 :(得分:3)

如果我没错,你的问题是你正在推送堆栈上的本地字符数组。 stack<char*>不会保存字符串,它会保存这些字符串的内存地址。当您将returnChar推入堆栈时,只保存地址,因此一旦您离开作用域并删除returnChar数组,保存的内存地址将指向已释放/未使用/垃圾内存。

解决此问题的最简单方法是使用stack<string>代替stack<char*>。 STL中的字符串将确保复制整个字符串,而不仅仅是地址变量的地址。

答案 1 :(得分:1)

这部分不能按预期工作:

char *token = strtok(cString, " ");
while(token !=NULL){
    if(isdigit(token[0])){
        valueStack.push(token);
    }

问题在于strtok返回的指针是一个临时指针,在下次调用strtok时会指向垃圾。

为了保存结果,您需要在令牌上执行strdup

valueStack.push(strdup(token));

虽然我强烈建议您在堆栈中使用std :: string而不是指针来避免内存泄漏,并避免使用c函数来分配内存。

std::stack<std::string> valueStack;
...
valueStack.push(token);