#include <iostream>
#include "ArrayStack.h"
#include <string>
usingnamespace std;
// Function prototype
bool checkallBraces(char []);
int main()
{
char * s;
s = newchar;
string input;
while (!(input == "q"))
{
cout << "This program checks if an expression is balanced.\nEnter expression: ";
cin >> s;
if (checkallBraces(s))
cout << "Expression is balanced!\n";
else
cout << "Expression isn't balanced!\n";
}
system("pause");
return 0;
}
bool checkallBraces(char s[])
{
char ch = '\0';
char stackItem = '\0';
bool balancedSoFar = true;
ArrayStack<char>* aStack = new ArrayStack<char>;
// iterate through each character in the string while checking continue
for (int i = 0; i < sizeof(s) && balancedSoFar; i++)
{
// set ch to current pos in string
ch = s[i];
// Ignore all characters but (, {, [, ], } and )
if ((ch == ')') || (ch == '(') || (ch == '}') || (ch == '{') || (ch == ']') || (ch == '['))
{
// process open brace
if (ch == '{' || ch == '(' || ch == '[')
{ // el error estaba aqui
aStack->push(ch);
}
// process closed brace
elseif (!aStack->isEmpty())
{
// peek into stack to find opening brace
stackItem = aStack->peek();
// try to match open and close delimiters of the same kind
if (((ch == ')') && (stackItem == '(')) || ((ch == '}') && (stackItem == '{')) || ((ch == ']') && (stackItem == '[')))
aStack->pop(); // Pop a matching open brace if found.
else // No matching open brace, Open and close parenthesis are not of the same type
balancedSoFar = false;
}
// Unmatched open and close parenthesis
else
balancedSoFar = false;
}
}
//return true if stack is empty and balanced
if (aStack->isEmpty())
return (true && balancedSoFar);
// else it isn't blanced
elsereturnfalse;
OUTPUT
This program checks if an expression is balanced.
Enter expression:{}
Expression is balanced!
// OK! NO PROBLEM !
This program checks if an expression is balanced.
Enter expression:{a{bc}
Expression isn't balanced!
// OK! NO PROBLEM!
This program checks if an expression is balanced.
Enter expression:{a{b}c}
Expression isn't balanced!
CAN SOMEONE EXPLAIN ME WHY IT ISN'T BALANCE ?
IT SUPPOSED TO BE BALANCED!
for (int i = 0; i < sizeof(s) && balancedSoFar; i++)
`s' is a pointer, sizeof is evaluated at compile time
so you may understand why you are not iterating the whole string.
you may use strlen(), check if s[i] is the terminator '\0' character, or use std::string that knows its size.
> ArrayStack<char>* aStack = new ArrayStack<char>;
1 2
ArrayStack<char> aStack; //construct an object
a.pop(); //use it as
Your logic is correct. The third case passed when I ran your code. http://cpp.sh/5tb2
I removed #include "ArrayStack.h" and used #include <vector> instead. Maybe something is wrong with ArrayStack?