2010-10-03 3 views
2

Le programme a été compilé avec succès, mais lorsque j'essaie de convertir l'expression infixe suivante 'A * B + C/D', j'obtiens ce message d'erreur: Erreur de segmentation (core dumped). Cela fonctionne pour une expression comme 'a + b-c * d/e' mais je ne sais pas si c'est correct ou non.infixe à postfix

#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; 
} 
+0

Quelle est la question? –

+0

Vous auriez pu simplifier ce code beaucoup avant de le poster. – Beta

Répondre

2

Vous avez:

while(precedence(operate)< precedence(mystack.top())) { // SEGV here. 
    postfix.append(mystack.top()); 
    mystack.pop(); 
} 

Vous devez vérifier s'il y a des éléments sur la pile avant de voir l'élément supérieur ou pop.

Changer

while(precedence(operate)< precedence(mystack.top())) 

à

while(!mystack.empty() && precedence(operate)< precedence(mystack.top())) 

travaillé.

+0

Merci codaddict pour souligner les erreurs – udaysubedi

Questions connexes