c++ - 将中缀表示法表达式转换为后缀表示法

标签 c++ stack notation infix-notation

我正在为我的数据结构类(class)做作业,我必须将中缀表达式转换为后缀表达式。我快完成了,但是当我尝试输入类似 a+b+c 的内容时,我总是收到错误

它可以很好地处理 a+b 和 a+b*c。

我真的不确定它有什么问题。如果有人能指出我的方向或发现我的代码存在问题,我将不胜感激。

#include <iostream>
#include <stack>

using namespace std; 

//checks priority of operators.
int priority(char e){
    int pri = 0; 

    if(e == '*' || e == '/' || e == '%'){
        pri = 2; 
    }else{
        if(e == '+' || e == '-'){
            pri = 1; 
        }
    }
    return pri; 
}

void main(){
    cout << "This program will convert an infix expression to a postfix expression." << endl; 
    cout << "Please enter your expression without any spaces." << endl; 

    stack<char> charStack; 

    char input[100]; 
    char output[100];
    char n1; 

    char *o; 
    o = &output[0]; 

    cin >> input; 

    int n = 0; 
    while(input[n] != 0){

        if(isdigit(input[n])  || isalpha(input[n])){
            *o = input[n]; 
            n++; 
            o++; 
        }

        if(input[n] == '('){
            charStack.push(input[n]); 
            n++;
        }

        if(input[n] == ')'){
            n1 = charStack.top(); 
            charStack.pop(); 
            while(n1 != '('){
                *o = n1; 
                o++; 
                n1 = charStack.top(); 
                charStack.pop(); 
            }
            n++; 
        }

        if(input[n] == '+' || input[n] == '-' || input[n] == '*' || input[n] == '/' || input[n] == '%'){
            if(charStack.empty() == true){
                charStack.push(input[n]);
            }else{
                n1 = charStack.top(); 
                charStack.pop(); 
                while(priority(n1) >= priority(input[n])){
                    *o = n1; 
                    o++;
                    n1 = charStack.top(); 
                    charStack.pop(); 
                }
                charStack.push(n1); 
                charStack.push(input[n]); 
            }
            n++; 
        }
    }
    while(!charStack.empty()){
        *o = charStack.top(); 
        o++; 
        charStack.pop(); 
    }
    *o = '\0'; 

    cout << output << endl; 

}

最佳答案

在运算符的代码中弹出元素之前不检查堆栈是否为空。这是问题的一部分。

顺便说一下,它应该是 int main() 而不是 void,而且你不需要与 true 进行比较: charStack.empty() == truecharStack.empty() 相同。

关于c++ - 将中缀表示法表达式转换为后缀表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4480239/

相关文章:

javascript - 如何让方法使用参数调用自身而不发生堆栈溢出

c++ - 现代 OpenGL 问题纹理平面

c++ - 如何执行运算符重载以避免 C++ 中的 if 条件?

c++ - 在qt中以最大化模式设置窗口标题

c++ - 堆栈弹出操作能否在 C++11 中安全地返回值

c++ - 在作用域生存期之前调用C++析构函数

matlab - 是否有比 `~isempty(x)` 更简单的方法将非标量 `x` 转换为 bool 标量?

javascript - Sciter 速记符号

Javascript:短时间表示法

c++ - 使用在外部类内部声明的数据类型