Question

please tell me what is it that I'm doing wrong? I need to make sure the expressions are balanced I tried everything but I don't even get errors

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;
}
Was it helpful?

Solution

One obivous problem -- your matcher function appears to return 1 for failure (does not match) and 0 for success, but your main prints ok if matcher returns non-zero...

OTHER TIPS

I will assume isOpener() and matches() work as intended, since you aren't showing them.

If so, the problem is that you're misinterpreting int -> bool conversions. A zero converts to false and a non-zero integer converts to true. You'd be better off declaring matcher() to return bool and return true or false from it directly. You'll want to return false there where you now return 1 and true there where you now return 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top