Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ program to check if the users input has the balanced braces. You nee

ID: 3630260 • Letter: W

Question

Write a C++ program to check if the users input has the balanced braces. You need to use the stack to implement the structure.Modify program below.

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

int main()
{
stack<int> aStack;

// Right now, the stack is empty
if (aStack.empty())
cout << "The stack is empty" << endl;

for (int j = 0; j < 5; j++)
aStack.push(j); // places items on top of stack

while (!aStack.empty())
{
cout << aStack.top() << " ";
aStack.pop();
} // end while
return 0;
} // end main

Explanation / Answer

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

int main()
{
stack<char> aStack;
string str;
char lPar='(';
char rPar=')';
char lBrac='[';
char rBrac=']';
bool isMatch=true;

// Right now, the stack is empty
if (aStack.empty())
cout << "Type in an equation or just hit <Enter> to exit: " << endl;

while(getline(cin, str) && str != "")
{
    isMatch=true;
    for (int x=0;x<str.length()&&isMatch;x++){
       
        if(str[x]!=' '){
            if((str[x]==lPar)||(str[x]==lBrac)) {
                aStack.push(str[x]);
            } else if(str[x]==rPar) {
                isMatch=false;
                while(!aStack.empty()&&(!isMatch)){
                    if(aStack.top()==lPar){
                        isMatch=true;
                    }
                    aStack.pop();
                }           
            } else if(str[x]==rBrac){
                isMatch=false;
                while(!aStack.empty()&&(!isMatch)){
                    if(aStack.top()==lBrac){
                        isMatch=true;
                    }
                    aStack.pop();
                }   
            } else if(!aStack.empty()){
                aStack.push(str[x]);
            }
        }       
    }
    if(!aStack.empty()||(!isMatch)) {
        cout<<str<< " is not matched"<<endl;
        while(!aStack.empty()){
            aStack.pop();
        }
    } else {
        cout<<str<< " is matched"<<endl;
    }
    cout << "Type in an equation or just hit <Enter> to exit: " << endl;
}

return 0;
} // end main

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote