2014-11-20 3 views
0

infixToPostfix (string infixExpr)를 작성하려고합니다. infix 표기법으로 표현식 문자열을 입력으로 받아 해당 표현식에 대한 접미사 표기법을 포함하는 문자열을 반환합니다. 중절 표기법은 괄호를 가질 수 있습니다. 이 연산자는 *, /, %, +, -, <, < =,> =,>, ==,! =, & &, || (이원 연산자 전용)논리 연산자가있는 접미사 - 코드 오류

여기는 내가 시도하는 코드입니다. parenthsis로 완벽하게 실행되지만 괄호없이 약간의 잘못된 출력을 제공합니다. 예를 들어 입력이 A + B/C이면 출력은 ABC/+가되어야하지만 대신 AB + C /를 제공합니다. 오류를 발견하도록 도와주세요. 감사합니다

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

using namespace std; 

// Function to convert Infix expression to postfix 
string InfixToPostfix(string expression); 
// Function to verify whether an operator has higher precedence over other 
int HasHigherPrecedence(string operator1, string operator2); 
// Function to verify whether a character is operator symbol or not. 
bool IsOperator(string C); 
// Function to verify whether a character is alphanumeric character (letter) or not. 
bool IsOperand(string C); 
int GetOperatorWeight(string opt); 
bool IsDoubleOperator(char c1, char c2); 



int main() 
{ 
    string expression; 
    cout<<"Enter Infix Expression \n"; 
    getline(cin,expression); 

    string postfix = InfixToPostfix(expression); 
    cout<<"Output = "<<postfix<<"\n"; 
    return 0; 
} 

// Function to evaluate Postfix expression and return output 
string InfixToPostfix(string expression) 
{ 
    // Declaring a Stack from Standard template library in C++. 
    stack<string> S; 
    string postfix = ""; // Initialize postfix as empty string. 
    for(int i = 0;i< expression.length();i++) { 
     string ex=""; 
     ex+=expression[i]; 

     // Scanning each character from left. 
     // If character is a delimitter, move on. 
     if(ex == " " || ex == ",") continue; 

     // If character is operator, pop two elements from stack, perform operation and push the result back. 
     else if(IsOperator(ex)) 
     { 
      while(!S.empty() && S.top() != "(" && HasHigherPrecedence(S.top(),ex)) 
      { 
       postfix+= S.top(); 
       S.pop(); 
      } 
      S.push(ex); 
     } 
     // Else if character is an operand 
     else if(IsOperand(ex)) 
     { 
      postfix +=ex; 
     } 

     else if (ex == "(") 
     { 
      S.push(ex); 
     } 

     else if(ex == ")") 
     { 
      while(!S.empty() && S.top() != "(") { 
       postfix += S.top(); 
       S.pop(); 
      } 
      S.pop(); 
     } 
     else if (IsDoubleOperator(expression[i], expression[i+1])) 
      { 
       string db=""; 
       string f=""; 
       db=+expression[i]; 
       f=+expression[i+1]; 
       db=db+f;  

       while(!S.empty() && S.top() != "(" && HasHigherPrecedence(S.top(),db)) 
       { 

        postfix+= S.top(); 
        S.pop(); 

       } 

       S.push(db); 
       i++; 
      } 
    } 

    while(!S.empty()) { 
     postfix += S.top(); 
     S.pop(); 
    } 

    return postfix; 
} 

// Function to verify whether a character is english letter or numeric digit. 
// We are assuming in this solution that operand will be a single character 
bool IsOperand(string C) 
{ 
    if(C >= "A" && C <= "Z") return true; 
    return false; 
} 

// Function to verify whether a character is operator symbol or not. 
bool IsOperator(string C) 
{ 
    if(C == "+" || C == "-" || C == "*" || C == "/" || C== "%") 
     return true; 

    return false; 
} 


// Function to get weight of an operator. An operator with higher weight will have higher precedence. 
int GetOperatorWeight(string op) 
{ 
    int weight = -1; 
    if(op=="&&"|| op=="||") 
     weight = 1; 

    if(op=="=="|| op=="!=") 
     weight = 2; 

    if(op=="<"|| op==">"|| op=="<="|| op==">=") 
     weight = 3; 
    if(op=="+"|| op=="-") 
     weight = 4; 


    if(op=="/"|| op=="%"|| op=="/") 
     weight = 5; 



    return weight; 
} 

// Function to perform an operation and return output. 
int HasHigherPrecedence(string op1, string op2) 
{ 
    int op1Weight = GetOperatorWeight(op1); 
    int op2Weight = GetOperatorWeight(op2); 

    // If operators have equal precedence, return true if they are left associative. 
    // return false, if right associative. 
    // if operator is left-associative, left one should be given priority. 

    if (op1Weight > op2Weight) 
     return op1Weight; 
    else 
     return op2Weight; 

} 
bool IsDoubleOperator(char c1, char c2) 
{ 
    string db=""; 
    string f=""; 
    db=+c1; 
    f=+c2; 
    db=db+f; 

    if (db=="&&" ||db=="||" || db==">=" || db=="<=" || db=="!=" ||db=="==") 
    { 

    //cout<<db; 
     return true; 
    } 

    return false; 
} 
+0

이제는 디버거를 사용하는 법을 배우는 것이 좋습니다. –

답변

0

HasHigherPrecedence (OP1가 OP2) OP1 그렇지 않으면 OP2하고 0보다 높은 우선 순위 (일명, 무게)이 때 아닌 0을 반환 할 것으로 예상된다. 그러나 그것은 일반적으로 0이 아닌 두 연산의 가중치의 최대 값을 반환합니다. 함수를 변경하여 함수가 반환되도록하면됩니다.

return op1Weight > op2Weight; 

true 일 때 1이고 false 일 때 0이됩니다. 이것은 당신의 운전자 단락을 수정해야합니다.