繁体   English   中英

我的中缀到后缀的程序给出了运行时错误

[英]My program of infix to postfix gives runtime error

下面是一个将中缀表达式转换为后缀表达式的简单程序。 它在主程序中接受一个中缀表达式,并在 function 转换器中传递值后,它以字符串形式返回一个后缀表达式。

#include<iostream>
#include<stdio.h>
#include<string>
#include <stack>
using namespace std;
int priority(char o) {
    if (o == '(' || o == ')')
        return -1;
    else if (o == '*' || o == '/')
        return 2;
    else if (o == '+' || o == '-')
        return 1;
    else if (o == '^' )
        return 3;
}
string converter(stack <char>s, string in) {
    string pf;
    int i;
    for (i = 0; i < in.length(); i++) {
        if ((in[i] >= 'a' && in[i] <= 'z') || (in[i] >= 'A' && in[i] <= 'Z') ){
            pf+= in[i];
        }
        else if (in[i] == '(') {
            s.push(in[i]);
        }
        else if (in[i] == ')') {
            while (s.top() != '(' && (!s.empty())) {
            char temp = s.top();
            pf += temp;
            s.pop();
            }
        }
        else  {
            if (s.empty()) {
                s.push(in[i]);
            }
            else {
                if (priority(in[i]) > s.top()) {
                    s.push(in[i]);
                }
                else if (priority(in[i]) == s.top()&&(in[i]=='^')) {
                    s.push(in[i]);
                }
                else {
                    while (priority(in[i]) <= s.top()&&(!s.empty())) {

                        char temp = s.top();
                        pf += temp;
                        s.pop();
                    }
                    s.push(in[i]);
                }
            }


        }
        
        }
    while (!s.empty()) {
        char temp = s.top();
        pf += temp;
        s.pop();
    }
        return pf;
    

}
int main() {
    string infix,postfix;
    cout << "input an infix expression"<<endl;
    cin >> infix;
    stack <char> s;
    postfix = converter(s, infix);
    cout << "Postfix expression is:" << postfix;
    return 0;
}

每次我尝试运行程序时,都会出现运行时错误。 它一直有效,直到采用中缀表达式,但 function 异常中止。 我找不到错误。 我使用视觉工作室。 这是我的视觉工作室的问题还是逻辑错误,真的不知道。

这一点:

while (priority(in[i]) <= s.top()&&(!s.empty()))

当堆栈为空时访问堆栈的顶部会调用未定义的行为,这正是这里发生的事情,因为priority(in[i]) <= s.top()将首先检查。

您应该首先移动.s.empty()条件。 如果它评估为真,则不会检查第二个条件。 这称为短路评估

while (!s.empty() && priority(in[i]) <= s.top())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM