[英]Error parsing an expression in C++
有人可以指出我的代碼中分段錯誤的原因。 我正在嘗試將具有由 '()' 決定的優先級的算術表達式轉換為后綴形式,然后求解該表達式。
#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]!=' ')
由於這兩個錯誤,您沒有正確地將值推送到堆棧中,在不同的時間得到錯誤的值,從而導致分段錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.