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

C++栈实现括号正确性校验 带空格输入误判问题求助

括号匹配程序问题修复方案

核心问题原因

带空格输入误判的问题,是输入读取逻辑的缺陷导致的:

  • 现有代码使用cin >> exp读取输入,该方法默认将空格、制表符、换行符作为输入分隔符,当你输入() (时,程序只会读取到第一个空格前的()存入exp变量,空格后的(完全没有进入后续判断逻辑,自然就误判为平衡。

修复方法

只需要把输入读取的代码替换为整行读取的getline方法,就能支持读取带空格的完整输入:

// 把原来的 cin >> exp; 替换为下面这行
getline(cin, exp);

额外优化建议

现有代码里有两处冗余和隐患可以调整,让程序更稳定简洁:

  1. 定义的show()函数全程没有被调用,可以直接删除
  2. 两次遍历字符串的逻辑可以合并为一次,同时完成栈操作和左右括号计数,不需要分开遍历两次
  3. 原有push方法的边界判断存在数组越界隐患,长度为10的数组下标最大为9,原来的top<10判断会导致写入Stack[10]的越界操作

修复后的完整可运行代码

#include <iostream>
#include <string>
using namespace std;

char Stack[10];
int top = -1;

void push(char ch)
{
    if (top < 9) {
        top++;
        Stack[top] = ch;
    } else {
        cout << "Stack Overflow";
    }
}

void pop()
{
    if (top > -1) {
        top--;
    } else {
        cout << "Stack Underflow";    
    }
}

int main(int argc, char** argv) 
{
    int a = 0, b = 0;
    string exp;
    cout << "Write down the parenthesis:" ;
    getline(cin, exp);
    bool check = true;
    
    for(int i = 0; i < exp.length(); i++)
    {
        if (exp[i] == '(') {
            push(exp[i]);
            a++;
        } else if (exp[i] == ')') {
            b++;
            if (top == -1) {
                check = false;
                break;
            } else {
                pop();
            }
        }
    }
    
    if (a != b || check == false) {
        cout << "\nGiven Combination is IMBALANCED";
    } else {
        cout << "\nGiven Combination is BALANCED";
    }
    
    return 0;
}

内容的提问来源于stack exchange,提问作者SHARIF ULLAH DANISH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:15:03