后缀表示法堆栈C++

Postfix notation stack C++

本文关键字:C++ 堆栈 表示 后缀      更新时间:2023-10-16

我是C++新手,我想使用堆栈来计算作为输入给出的表达式(例如 2+3*5+4),仅包含数字、+ 和 *。我写了这段代码,但它给了我分段错误:11。你能帮我解决这个问题或给我一个提示,说明可能出了什么问题吗?谢谢!(我注意到这个网站上有类似的问题,但我无法使用它们来解决我的问题)

#include <iostream>
#include <stack>
using namespace std;
bool highPrecedence(char a, char b){
    if((a=='+')&&(b=='*'))
        return true;
    return false;
}
int main()
{
    char c = 'a';
    double x;
    stack<char> stack;
    double v[10];
    int i=0;
    double res;
    while(true)
    {
        c = cin.get();
        if(c=='n'){
            while(stack.size()!=0){
                if (stack.top()=='*'){
                    double res = v[i]*v[i-1];
                    i--;
                    v[i]=res;
                    stack.pop();
                }
                if (stack.top()=='+'){
                    res = v[i]+v[i-1];
                    i--;
                    v[i]=res;
                    stack.pop();
                }
            }
            break;
        }
        if ( '0'<=c && c<='9' )
        {
            cin.putback(c);
            cin>>x;
            cout<<"Operand "<<x<<endl;
            i=i+1;
            v[i]=x;
        }
        else
        {
            if(c!=' ') cout<< "Operator " <<c<<endl;
            if (stack.size()==0)
                stack.push(c);
            else{
                while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
                    if (stack.top()=='*'){
                        double res = v[i]*v[i-1];
                        i--;
                        v[i]=res;
                        stack.pop();
                    }
                    if (stack.top()=='+'){
                        res = v[i]+v[i-1];
                        i--;
                        v[i]=res;
                        stack.pop();
                        }
                    }
                stack.push(c);
                }
            }
        }

    cout<<v[0]<<endl;
}
  • 如果stack为空,则使用 stack.top() 是非法的。
    更改while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
    while((!stack.empty()) && (!highPrecedence(stack.top(),c))){
  • i 的初始值不好,您正在打印具有不确定值的未初始化变量。
    int i=0;更改为int i=-1;