繁体   English   中英

解析 C++ 中的表达式时出错

[英]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.

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