gpt4 book ai didi

c++ - 在 C++ 中解析表达式时出错

转载 作者:行者123 更新时间:2023-11-30 05:18:41 25 4
gpt4 key购买 nike

有人可以指出我的代码中出现段错误的原因吗?我正在尝试将优先级由“()”决定的算术表达式转换为后缀形式,然后求解该表达式。

#include<iostream>
#include<string>
#include<stack>

using namespace std;

string post(string exp)
{
cout<<"reached post";
stack<char> s2;
string new_exp="";
int length=exp.length();
for(int i=0; i<length; i++)
{
if(exp[i]=='(')
{
s2.push(exp[i]);
}
else if(exp[i]=='+'|| exp[i]=='-' || exp[i]=='*' || exp[i]=='/')
{
new_exp+=' ';
s2.push(exp[i]);
}
else if(exp[i]>='0'&& exp[i]<='9')
{
new_exp+=exp[i];
}
else if(exp[i]==')')
{
new_exp+=' ';
new_exp+=s2.top();
s2.pop();
s2.pop();
}
}
if(!s2.empty())
{
while(!s2.empty())
{
new_exp+=' ';
new_exp+=s2.top();
s2.pop();
}
}

return(new_exp);
}

int operation(char op, char op1, char op2)
{
if(op == '+') return(op1+op2);
else if(op=='-') return(op1-op2);
else if(op=='*') return(op1*op2);
else if(op=='/') return(op1/op2);
}

int solve(string expression)
{
cout<<"\nreached solve";
string postfix=post(expression);
stack<char> s;
int res;
int length=postfix.length();
for(int i=0; i<length; i++)
{
if(postfix[i]==' ')
{
continue;
}
else if(postfix[i]=='+'|| postfix[i]=='-' || postfix[i]=='*' || postfix[i]=='/')
{
char op2=s.top();
s.pop();
char op1=s.top();
s.pop();
res=operation(postfix[i],op1,op2);
s.push(res);
}
else if(postfix[i]>='0' && postfix[i]<=9)
{
int operand=0;
while(postfix[i]!=' ' || i!=length)
{
operand=(operand*10)+(postfix[i]-'0');
i++;
}
i--;
s.push(operand);
}
}
return(res);
}

int main(void)
{
string exp;
int result;
cout<<"Enter expression: ";
getline(cin,exp);
result=solve(exp);
cout<<"\nResult= "<<result;
return 0;
}

我收到以下错误消息:

cav@cav-VirtualBox:~/src/cpp$ ./infix_postfix
Enter expression: 10+3

Segmentation fault (core dumped)

最佳答案

我至少可以看到两个错误。首先,

else if(postfix[i]>='0' && postfix[i]<=9)

您需要比较字符 '9',而不是整数 9,因为这里有一个字符串。应该是:

else if(postfix[i]>='0' && postfix[i]<='9')
^ ^

第二个问题在这里:

while(postfix[i]!=' ' || i!=length)

你在这里的意思是操作&&,而不是||。当它是 || 时,它基本上适用于所有字符,除了 i 超出了长度。此外,i != length 应该在 postfix[i] != ' ' 之前进行测试,因为 i == length postfix[i ] 将越界。这一行应该是:

while(i!=length && postfix[i]!=' ')

由于这两个错误,您没有正确地将值推送到您的堆栈,在不同的时间获得错误的值,这会导致段错误。

关于c++ - 在 C++ 中解析表达式时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41541165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com