Question

Balanced braces using stack program please help correct program

This program needs to be corrected. It states that the equation is matched when you enter } { and it should not. I can not find the error.

#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

Solutions

Expert Solution
No answers


Submit Your Answer