So MOST of it is working out properly so far...until I get to this point. I'm supposed to check if brackets/braces are balanced. My code is below for the function definition:
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include "assignment4.h"
usingnamespace std;
typedefbool boolean;
namespace assignment4
{
// Precondition: Each character of string p is '(', ')', '{' or '}'.
// Postcondition: The method returns true if the characters form a
// sequence of correctly balanced parentheses with each '('
// matching a ')' and each '{' matching a '}'. Note that a
// sequence such as ( { ) } is NOT balanced. On the other hand,
// ( { } ) and { ( ) } are both balanced.
boolean balanced(char* p)
{
// Push an open brace/bracket onto the stack
// Once it reaches a closed brace, pop it off and THEN compare/check
// Stack needs to be empty at the end
// If it's even and if the stack's empty, it's balanced--return true
// Declares a stack of chars for *p
stack<char> charstack;
// Checks if the string is an even number first
if ((strlen(p) % 2) != 0)
{
returnfalse;
}
// Continues to push or pop using a for loop
for (size_t i = 0; p[i] != '\0'; i++)
{
// If the char is a { or a (, push it onto charstack
if (p[i] == ('(' || '{'))
{
charstack.push(p[i]);
}
// If the char is a } or a )
elseif ((p[i] == (')' || '}')) && (!charstack.empty()))
{
if ((p[i] == ')') && (charstack.top() == '('))
{
charstack.pop();
}
elseif ((p[i] == '}') && (charstack.top() == '{'))
{
charstack.pop();
}
// Otherwise, if these two conditions aren't met, then the parentheses must not match; return false
else
{
returnfalse;
}
}
// _____________________________________________________________________
elsereturnfalse;
}
// If the stack is empty AND the number of chars in the string were even, return true
if (charstack.empty())
{
returntrue;
}
// If the stack is NOT empty or the number of chars in the string were odd, return false
returnfalse;
}
}
And the char array that's calling this function is: char str4[20] = "{(({))}}";
It should be returning a false and NOT a true, since the brackets do not match up properly. Can anyone help me?
EDIT: I added a new line of code that seemed to fix the problem (See the underscored comment in the code), but now it's saying that THIS char array is unbalanced: char str1[20] = "({({}{()})()})";