You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ If-else if逻辑错误:不匹配分组符号被误判为匹配

算术表达式分组符号匹配逻辑漏洞排查与修复

问题根源

你的代码存在两个核心逻辑漏洞:

  1. 未处理不匹配的闭合符号:当遇到像}这种闭合符号,但栈顶是[时,代码直接跳过该字符,没有判定为不匹配。比如输入1+[1}]中的},既不满足左符号压栈的条件,也不满足else if里的匹配弹栈条件,所以被忽略;后续]和[匹配弹栈后栈为空,错误判定为匹配。
  2. 未提前终止错误判定:一旦发现不匹配的情况,没有立即终止遍历并返回结果,而是继续执行,导致后续操作干扰最终判断。

修复后的代码

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

using namespace std;

void matchingSymbol(string);

int main()
{
    matchingSymbol("{25+(3-6)*8}"); // 匹配
    matchingSymbol("7+(8*2");       // 不匹配
    matchingSymbol("1+[1}]");       // 不匹配

    string input;
    cout << "Enter an arithmetic to check for matching grouping symbols: ";
    cin >> skipws >> input;
    matchingSymbol(input);
}

void matchingSymbol(string arithInput)
{
    stack<char> tempStr;
    bool isMatched = true; // 标记遍历过程中是否出现不匹配

    for (int i = 0; i < arithInput.length(); i++) {
        char c = arithInput.at(i);
        if (c == '{' || c == '(' || c == '[') {
            tempStr.push(c);
        }
        else if (c == '}' || c == ')' || c == ']') {
            // 空栈直接判定不匹配
            if (tempStr.empty()) {
                isMatched = false;
                break;
            }
            char top = tempStr.top();
            // 闭合符号与栈顶左符号不匹配,直接判定不匹配
            if ((c == '}' && top != '{') || 
                (c == ')' && top != '(') || 
                (c == ']' && top != '[')) {
                isMatched = false;
                break;
            }
            // 匹配则弹栈
            cout << "Popped for arithInput: " << c << " and tempStr: " << top << "\n";
            tempStr.pop();
        }
        // 数字、运算符等非分组符号直接跳过
    }

    // 最终需同时满足:遍历无错误 + 栈中无剩余左符号
    if (isMatched && tempStr.empty()) {
        cout << arithInput << " --> " << "Groupings matched.\n";
    }
    else {
        cout << arithInput << " --> " << "Groupings not matched.\n";
    }
}

修复关键点

  • 新增isMatched变量,实时标记遍历过程中是否出现不匹配;
  • 单独处理所有闭合符号:遇到闭合符号时先检查栈是否为空(空栈意味着无对应左符号),再验证与栈顶左符号的匹配性,不匹配则立即终止遍历;
  • 最终判断需同时满足遍历无错误和栈为空两个条件,确保所有左符号都有对应且顺序正确的右符号。

测试验证

运行修复后的代码,输入1+[1}]会输出:

1+[1}] --> Groupings not matched.

符合预期判定结果。

内容的提问来源于stack exchange,提问作者redpocket

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:37:47