如何找到错误的中缀表达式?

时间:2015-06-30 12:35:32

标签: c++ data-structures stack

我必须将中缀表达式转换为后缀。我的中缀到Postfix代码工作没有任何错误。但我还必须找到错误的中缀表达式。如何解决这个问题呢?

这是我的代码:(我使用了自定义堆栈文件)

#include <iostream>
#include <string>
#include "stacktype.cpp"
using namespace std;

string infixToPostFix(string infix);
int higherPrecedenceValidate(char op1, char op2);
int getPrecedence(char op);
int evaluatePostFix(string postfix);

int main()
{
    string infix,postfix;
    int result;
    cin >> infix;
    postfix = infixToPostFix(infix);
    cout << postfix <<endl;
    result = evaluatePostFix(postfix);
    cout << "result: " << result << endl; 

}


string infixToPostFix(string infix){
    StackType<char> operators;
    string postfix;
    for(int i = 0; i < infix.size(); i++){
        // Checking Operator
        if(infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/'){
            while (!operators.IsEmpty() && higherPrecedenceValidate(operators.Top(),infix[i]))
            {
                postfix = postfix + operators.Top();
                operators.Pop();
            }
            operators.Push(infix[i]);

        }
        // Checking Operand
        else if(infix[i] >= '0' && infix[i] <= '9')
        {
            postfix = postfix + infix[i];

        }
        //Checking open bracket
        else if(infix[i] == '(' ){
            operators.Push(infix[i]);
        }

        //Checking closing bracket
        else if(infix[i] == ')' ){
            while (!operators.IsEmpty() && operators.Top() != '(')
            {
                postfix = postfix + operators.Top();
                operators.Pop();
            }
            // poping the opening bracket
            operators.Pop();
        }


    }
    // poping rest of element from the stack..
    while (!operators.IsEmpty())
    {
        postfix = postfix + operators.Top();
        operators.Pop();
    }
    return postfix;
}

int evaluatePostFix(string postfix){
    StackType<int> finalNumbers;
    for(int i = 0; i < postfix.size(); i++){
        // Checking Operator
        if(postfix[i] == '+' || postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/'){
            int resultOfTwoNumber;
            int number2 = finalNumbers.Top();
            finalNumbers.Pop();
            int number1 = finalNumbers.Top();
            finalNumbers.Pop();
            switch (postfix[i])
            {
                case '+':
                    resultOfTwoNumber = number1 + number2;
                    break;
                case '-':
                    resultOfTwoNumber = number1 - number2;
                    break;
                case '*':
                    resultOfTwoNumber = number1 * number2;
                    break;
                case '/':
                    resultOfTwoNumber = number1 / number2;
                    break;
            }
            finalNumbers.Push(resultOfTwoNumber);

        }
        // Checking Operand
        else if(postfix[i] >= '0' && postfix[i] <= '9')
        {
            finalNumbers.Push(postfix[i] - '0');

        }
    }
    return finalNumbers.Top();
}


int higherPrecedenceValidate(char operator1, char operator2)
{
    int op1 = getPrecedence(operator1);
    int op2 = getPrecedence(operator2);
    if(op1 == op2)
        return true;
    return op1 > op2 ?  true: false;
}

int getPrecedence(char op)
{
    int weight = 0;
    switch(op)
    {
    case '+':
    case '-':
        weight = 1;
        break;
    case '*':
    case '/':
        weight = 2;
        break;
    }
    return weight;
}
  

现在我解决了这个问题。这是我错误的中缀表达式检查代码,中缀为postfix,后缀为结果评估:

#include <iostream>
#include <string>
#include "stacktype.cpp"
using namespace std;

string infixToPostFix(string infix);
int higherPrecedenceValidate(char op1, char op2);
int getPrecedence(char op);
int evaluatePostFix(string postfix);

int main()
{
    string infix,postfix;
    int result;
    cout << "Infix: ";
    cin >> infix;
    postfix = infixToPostFix(infix);
    cout << "\nPostfix: " << postfix << endl << endl;
    if(postfix != "Wrong Expression"){
        result = evaluatePostFix(postfix);
        cout << "Result: " << result << endl << endl; 
    }


}


string infixToPostFix(string infix){
    StackType<char> operators;
    bool isMathOperatorRepeated = false;
    bool isOperaendRepeated = false;
    string postfix;
    for(int i = 0; i < infix.size(); i++){
        // Checking Operator
        if(infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/'){
            if(isMathOperatorRepeated){
                postfix = "Wrong Expression";

                /* 
                After this for loop there is while loop
                which is checking rest of the char and add it with postfix string .
                So this pushed char should be pop out 
                beacuse infix expression is wrong.
                */

                while (!operators.IsEmpty())
                {
                    operators.Pop();
                }
                break;
            }
            while (!operators.IsEmpty() && higherPrecedenceValidate(operators.Top(),infix[i]))
            {
                postfix = postfix + operators.Top();
                operators.Pop();
            }
            operators.Push(infix[i]);
            isMathOperatorRepeated = true;
            isOperaendRepeated = false;

        }
        // Checking Operand
        else if(infix[i] >= '0' && infix[i] <= '9')
        {
            if(isOperaendRepeated){
                postfix = "Wrong Expression";

                /* 
                After this for loop there is while loop
                which is checking rest of the char and add it with postfix string .
                So this pushed char should be pop out 
                beacuse infix expression is wrong.
                */

                while (!operators.IsEmpty())
                {
                    operators.Pop();
                }
                break;
            }
            postfix = postfix + infix[i];
            isMathOperatorRepeated = false;
            isOperaendRepeated = true;

        }
        //Checking open bracket
        else if(infix[i] == '(' ){
            operators.Push(infix[i]);
            isMathOperatorRepeated = false;
            isOperaendRepeated = false;
        }

        //Checking closing bracket
        else if(infix[i] == ')' ){

            while (!operators.IsEmpty() && operators.Top() != '(')
            {
                postfix = postfix + operators.Top();
                operators.Pop();
            }

            /*
            checking stack beacuse we know 
            that if the infix char is ')'  
            and the stack is empty then the infix expression is wrong

            */
            if(operators.IsEmpty()){
                postfix = "Wrong Expression";
                break;

            }
            else{
                operators.Pop();
            }
            // poping the opening bracket
            isMathOperatorRepeated = false;
            isOperaendRepeated = false;
        }

        // checking that infix expression has invalid char
        else{
            postfix = "Wrong Expression";

            /* 
                After this for loop there is while loop
                which is checking rest of the char in stack.
                So this pushed char should be pop out 
                beacuse infix expression is wrong.
            */
            while (!operators.IsEmpty())
            {
                operators.Pop();
            }
            break;
        }


    }
    // poping rest of element from the stack..
    while (!operators.IsEmpty())
    {
        if(operators.Top() == '('){
            postfix = "Wrong Expression";
            break;
        }
        else{
            postfix = postfix + operators.Top();
            operators.Pop();
        }
    }
    return postfix;
}

int evaluatePostFix(string postfix){
    StackType<int> finalNumbers;
    for(int i = 0; i < postfix.size(); i++){
        // Checking Operator
        if(postfix[i] == '+' || postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/'){
            int resultOfTwoNumber;
            int number2 = finalNumbers.Top();
            finalNumbers.Pop();
            int number1 = finalNumbers.Top();
            finalNumbers.Pop();
            switch (postfix[i])
            {
                case '+':
                    resultOfTwoNumber = number1 + number2;
                    break;
                case '-':
                    resultOfTwoNumber = number1 - number2;
                    break;
                case '*':
                    resultOfTwoNumber = number1 * number2;
                    break;
                case '/':
                    resultOfTwoNumber = number1 / number2;
                    break;
            }
            finalNumbers.Push(resultOfTwoNumber);

        }
        // Checking Operand
        else if(postfix[i] >= '0' && postfix[i] <= '9')
        {
            finalNumbers.Push(postfix[i] - '0');

        }
    }
    return finalNumbers.Top();
}


int higherPrecedenceValidate(char operator1, char operator2)
{
    int op1 = getPrecedence(operator1);
    int op2 = getPrecedence(operator2);
    if(op1 == op2)
        return true;
    return op1 > op2 ?  true: false;
}

int getPrecedence(char op)
{
    int weight = 0;
    switch(op)
    {
    case '+':
    case '-':
        weight = 1;
        break;
    case '*':
    case '/':
        weight = 2;
        break;
    }
    return weight;
}

1 个答案:

答案 0 :(得分:1)

在进行转换时,您应该检查以下几项内容,以确定中缀表达式是否有效:

  • 将最后的else添加到确定字符类型的链中,即操作符,数字或括号。当字符未被识别时,您的代码将触及该分支,这意味着中缀表达式无效。您可能需要添加另一个&#34;有效&#34;分支允许空格。
  • 添加一项检查,以查看运算符前面是另一个运算符,如2 + * 3中所示。您可以使用&#34中设置的bool标记来执行此操作;这是一个运算符&#34;分支,并在其他地方重置。
  • 在弹出左括号之前,先检查堆栈是否为空。它上面的while循环可以结束有两个原因 - 堆栈变空,或者找到相应的左括号。如果循环因为堆栈为空而结束,则表达式段具有比打开括号更多的右括号,并且表达式无效。
  • 添加一项检查,确保您在最终&#34;展开期间没有弹出任何操作符&#34;堆栈的括号是一个括号。如果在结尾处在堆栈上找到括号,则表达式具有比右括号更多的左括号,因此它是无效的。

当您检测到表达式无效时,抛出异常,或返回特殊string以指示转换失败。