инфикс в постфикс с логическими операторами - ошибка кода

0

im пытается написать строку функций InfixToPostfix (string infixExpr), которая принимает в качестве входных данных строку выражения в нотации infix и возвращает строку, содержащую нотацию постфикса для этого выражения. Инфиксная нотация может иметь скобки. Программа должна обрабатывать эти операторы *,/,%, +, -, <, <=,> =,>, ==,! =, &&, || (только для двоичных операторов)

Вот код, который я пытаюсь... его работа отлично работает с партентизмом, но дает неправильный вывод без круглых скобок. например, если вход 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
    Сейчас будет отличное время, чтобы научиться использовать отладчик.
Теги:
stack

1 ответ

0

Предполагается, что HasHigherPrecedence (op1, op2) возвращает ненулевое значение, если op1 имеет более высокий приоритет (вес AKA), чем op2, и ноль в противном случае. Однако он возвращает максимум двух весов ops, который обычно отличен от нуля. Вам просто нужно изменить функцию так, чтобы она возвращалась:

return op1Weight > op2Weight;

Который будет 1, когда true и zero, когда false. Это должно привести к отключению вашего оператора.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню