2

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

}
4

2 回答 2

1

请参阅我的内联评论。

// 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(); 
于 2010-12-18T22:46:56.433 回答
1

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

顺便说一句,它应该是int main()代替void,你不需要比较事物与true:charStack.empty() == true是一样的charStack.empty()

于 2010-12-18T22:56:38.240 回答