首页 > 解决方案 > 我的有效表达式检查器中的扭结

问题描述

很明显,我的有效表达式运算符遇到了一些问题。理论上,我理解首先检查范围开启器的概念,如果您看到没有范围开启器的范围更近,那么它是无效的。我不太确定它是我绘制的图表还是什么,但就像我说的那样,在编码时使用算法时我只是有点困惑,有什么提示吗?另外,我的教授告诉我在这里使用案例切换?这对我有什么好处?当实际上我只需要一个 if 语句时,我不需要为范围开启器和关闭器提供 3 个不同的 case 开关吗?

 //=============use case switch here
    void check_expression(char expression[80], bool& valid)
    {
        Stack symbStack;  //stack to hold scope openers
        char symbol, //current symbol in the expression being investigated
        top_symb;  //current scope opener at the top of the stack
        int i = 0; //subscript to element in expression array, initialized to
                   //first element 

        valid = true;  
        symb = expression[i];
        while(symb != '\0') //while symbol in expression is not the null terminator
        {
                if( symbol == '{' || symbol == '[' || symbol == '(' )
                {
                    symbStack.Push(symbol);
                }

                else if( symbol == '}' || symbol == ']' || symbol == ')' )
                {
                    if(symbStack.IsEmpty())
                    {
                        cout << "Expression is invalid!";
                        valid == false;
                    }

                    else
                    {
                        top_symb = symbStack.StackTop();
                        symbStack.Pop();

                        if(  (top_symb == '(' && symbol != ')') ||  
                             (top_symb == '[' && symbol != ']') ||
                             (top_symb == '{' && symbol != '}')   )
                        {
                            valid = false;
                        }
                    }
                }
                i++;  //incrememt the subscript to the next character in the expression.
                symb = expression[i]; //assign symb to the next character in expression.
        }

        //Check to see if the stack is not empty.  If it is not empty, then 
        //the expression is invalid, in which case you want to assign valid to false
        return;
    }

标签: c++validationstack

解决方案


valid == false;
     ^^^^

有你的罪魁祸首。摆脱其中一个,=你应该会很好。

作为旁注,如果您意识到您正在查看无效的表达式,您可以立即返回!在那之后,表达式无法变为有效。因此,您可以return;在设置validfalse.


推荐阅读