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

C++ 将中缀表示法表达式转换为后缀表示法,c++,stack,notation,infix-notation,C++,Stack,Notation,Infix Notation,我正在为我的数据结构课程做一项作业,我必须将中缀表达式转换为后缀表达式。我差不多完成了,但当我尝试输入a+b+c之类的内容时,我总是会出错 它可以很好地处理a+b和a+b*c 我真的不知道它出了什么问题。如果有人能为我指明方向或看到我的代码存在的问题,我将非常感激 #include <iostream> #include <stack> using namespace std; //checks priority of operators. int priority

我正在为我的数据结构课程做一项作业,我必须将中缀表达式转换为后缀表达式。我差不多完成了,但当我尝试输入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; 

}
#包括
#包括
使用名称空间std;
//检查操作员的优先级。
整数优先级(字符e){
int-pri=0;
如果(e='*'| | e='/'| | e=='%')){
pri=2;
}否则{
如果(e=='+'| | e=='-'){
pri=1;
}
}
返回优先级;
}
void main(){

无法在线查看我的评论

// You can empty the stack here.
charStack.pop(); 

while(priority(n1) >= priority(input[n])){
    ...

    // BUG: This line will crash if the stack is empty.
    // You need to check for an empty stack.
    n1 = charStack.top(); 

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


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

相同,谢谢你的回复。:D与上面的人一样,但我很感激。