在抛出 what() 的实例后终止调用'std::out_of_range':basic_string::at

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at

本文关键字:out of range at string basic std what 实例 终止 调用      更新时间:2023-10-16

使用命名空间std;

class stack
{
char data[30];
int top;
public:
void init()
{
    top=-1;
}
int is_empty();
void push(char);
char pop();
int precedence(char);
};
int stack::is_empty()
{
if(top==-1)
    return(1);
return 0;
}
void stack::push(char op)
{
top++;
data[top]=op;
}
char stack::pop()
{
char x;
x=data[top];
top--;
return(x);
}
int stack::precedence(char op)
{
if(op=='(')
    return(1);
if(op=='+' || op=='-')
    return(2);
if(op=='*' || op=='/' || op=='%')
    return(3);
if(op=='^')
    return(4);
return(5);
}
int main()
{
stack s;
string iexp,pexp;
int i,j;
j=0;
char op;
s.init();
cout<<"n enter an infix expr.: ";
cin>>iexp;
for(i=0;i<iexp.length();i++)
{
    if(isalpha(iexp.at(i)))
    {
        pexp.at(j)=iexp.at(i);
        j++;
    }
    else
    {
        if(s.is_empty())
        {
            s.push(iexp.at(i));
        }
        else
        {
            if(iexp.at(i)=='(')
            {
                s.push(iexp.at(i));
            }
            if(iexp.at(i)==')')
            {
                while((op=s.pop())!='(')
                {
                pexp.at(j)=op;
                j++;
                }
            }
        while(s.precedence(iexp.at(i))<=s.precedence((op=s.pop())))
            {
                pexp.at(j)=op;
                j++;
            }`
        s.push(iexp.at(i));
        }
    }
 ``}
while(!s.is_empty())
{
    op=s.pop();
    pexp.at(j)=op;
    j++;
}
pexp.at(j)='';
cout<<"n postfix expr. is : t"<<pexp;
return 0;
}

我是编程新手。我正在进行中缀到后缀的转换,但遇到了错误:

  terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at

所以请帮我解决这个问题。

我不认为您可以使用附加到字符串

pexp.at(j) = ...;

尝试使用

pexp += ...; 

相反(在所有附加到pexp的地方(