Check for Balanced Parenthesis in a Stack
The problem is: Read in a string representing an expression that contains parentheses and have your program print that string and report whether or not the parentheses are correctly balanced.
Examples: This input string this output statement.
( a + b ) / 9 ( a + b ) / 9 is balanced
) a + b ( ) a + b ( is NOT balanced
((x-y)/(9-z) ((x-y)/(9-z) is NOT balanced
noparens noparens is balanced
(((x-y)/(9-z))) (((x-y)/(9-z))) is balanced
The problem I'm having right now is that my program says example 2 is balanced even though the closed parens comes first. Here is the code that goes through the stack and checks if the parens are balanced or not.
char stackChar = ' ';
int count = 0;
while(!stack1.empty() && count != -1) //until stack empty and while closed parens always follow open parens
stackChar = stack1.pop(); //get top char
if(stackChar == '(') //if open parens, increment count
if(stackChar == ')') //if closed parens, decrement count
If the closed parenthesis goes first, the program is still saying it's balanced. Why is this still happening? Thanks.