平衡的表达与堆栈

balanced expression with stacks

本文关键字:堆栈 平衡      更新时间:2023-10-16

请告诉我我做错了什么?我需要确保表情平衡我试了所有方法,但都没有错误

int main() {
    ifstream infile;
    infile.open("input.txt");
    string exp;
    cout << "Enter an expression ";
    while (getline(infile, exp)) {
        cout << exp << ": ";
        if (matcher(exp))
            cout << "Matched ok" << endl;
        else
            cout << "Match error" << endl;
        cout << "Enter an expression: ";
    }
    cout << "--- Done ---" << endl;
    return 0;
}
int matcher(string expression) {
    stack<char> s;
    for (int i = 0; i < expression.length(); i++) {
        if (isOpener(expression[i]))
            s.push(expression[i]);
        else if (isCloser(expression[i])) {
            if (s.empty()) return 1;    
            char opener = s.top();
            s.pop();
            if (!matches(opener, expression[i])) return 1;
        }
    }
    if (!s.empty()) return 1;
    return 0;
}

一个明显的问题-您的matcher函数似乎返回1失败(不匹配)和0成功,但您的main打印ok如果matcher返回非零…

我将假定isOpener()matches()正常工作,因为您没有显示它们。

如果是这样,问题是你误解了int -> bool转换。零转换为false,非零整数转换为true。您最好声明matcher()返回bool,并直接从中返回truefalse。您将希望在现在返回1的地方返回false,在现在返回0的地方返回true