In: Computer Science
Using STL stack class, implement in C++ a function that checks for balanced braces { }, in a given string / arithmetic expressions.
Program Code Screenshot
Program Sample Console Input/Output Screenshot

Program Code to Copy
#include <bits/stdc++.h>
using namespace std;
int main()
{
        // declare variable to store expression
        string exp;
        // prompt user for input
        cout << "Enter an expression containg curly braces {}:  ";
        //read expression from user consisting of {} braces
        cin >> exp;
        // declare stl stack
        stack<char> stck;
        // variable to keep track if expression is balanced or not
        bool balanced = true;
        // evaluate expression
        int pos = 0;
        while (pos < exp.size())
        {
                // if opening bracket, then push in stack
                if (exp[pos] == '{')
                {
                        stck.push(exp[pos]);
                }
                else if (exp[pos] == '}')
                {
                        // if closing bracket then stack top must be opening bracket
                        // if yes pop it, otherwise break with failure
                        if (!stck.empty() && stck.top() == '{')
                        {
                                stck.pop();
                        }
                        else
                        {
                                break;
                                balanced = false;
                        }
                }
                pos++;
        }
        // show output
        cout << "Given expression " << exp << " is" << (balanced && stck.empty() ? " balanced" : " not balanced") << endl;
}