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

问题描述

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

#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;
}

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

解决方法

这一点:

document.addEventListener('onEventReceived',function(obj) {
  setTimeout(function(){
    var listItems = document.querySelectorAll(".listItem");
    var listItemNew = listItems[0];
    SetListItem(listItemNew);
    
  },10000);
});

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

您应该先移动 priority(in[i]) <= s.top() 条件。如果它评估为真,则不会检查第二个条件。这称为Short-circuit evaluation

!s.empty()

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...