首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >infix到后缀

infix到后缀
EN

Stack Overflow用户
提问于 2010-10-03 03:34:17
回答 1查看 8.9K关注 0票数 2

程序编译成功,但是当我试图转换以下infix表达式'A *B+C/ D‘时,我会得到以下错误消息:分段错误(内核转储)。它适用于像‘a+b-c*d/e’这样的表达式,但我不知道它是否正确。

代码语言:javascript
复制
#include<iostream>
#include<stack>
#include<string>
using namespace std;

string infix;  // infix exression string
string operand;
string operate;
stack <string> mystack; // this stack is used to push the operator
string postfix;  // postfix string where the operand is appended

//....................................................................
// this function read the infix expression from user 
string input()
{
 cout<<" Enter the damn infix expression: "<<endl; 
 getline(cin, infix);
 return infix;
}
//......................................................................
// this function checks for operator precedency in the stack
int precedence(string e)
{
int f;
if(e == "*" || e== "/" || e =="%")
 f = 2;
else
{
if(e == "+" || e == "-")
 f = 1;
}

if(e=="."){
f=0;
}

return f;

}




//....................................................................
// This function converts infix to postfix
string convert()
{ 
 for(int i=0; i<infix.length(); i++)
 { 

 switch(infix[i]){

 // operate case start  
 case '+': case'-': case'*': case'/': case'^': case '(': case ')': case'.':

 operate=infix[i];
 {
  if(mystack.empty() || precedence(operate)>= precedence(mystack.top()))
  {
   mystack.push(operate);    
   break;
  }       

  else 
  {
   while(precedence(operate)< precedence(mystack.top()))
   {
    postfix.append(mystack.top());
    mystack.pop();
   }

   mystack.push(operate); 


  }
 }//operate case closed

 default:        //when operand string char is parsed
  {
                        operand=infix[i];
                        postfix.append(operand);
                        break;

  } // default case closed

 }//switch closed

 }// for loop close

 while(!mystack.empty())
 {
  postfix.append(mystack.top());
  mystack.pop();
 }

return postfix;
cout<<postfix;

} // function close braces



//...................................................................
int main()
{

input();

convert();
cout<<"postfix is "<<postfix<<endl;
} 
EN

回答 1

Stack Overflow用户

发布于 2010-10-03 03:40:17

你有:

代码语言:javascript
复制
while(precedence(operate)< precedence(mystack.top())) { // SEGV here.
  postfix.append(mystack.top());
  mystack.pop();
}

在看到顶部的元素或pop之前,您需要检查堆栈中是否有元素。

改变

代码语言:javascript
复制
while(precedence(operate)< precedence(mystack.top()))

代码语言:javascript
复制
while(!mystack.empty() && precedence(operate)< precedence(mystack.top()))

起作用了。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3848468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档