Balanced Parentheses Problem

I actually have two issues with the program, one that is my fault and the other is just an assignment problem.

The following is my code for checking an expression if the curly brackets, brackets, and parentheses are balanced. The code runs but I'm having an issue with the parentheses. It keeps telling me that they are not balanced when I clearly put a ( and a ).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <stack>
#include <string>

using namespace std;

// checks whether or not two characters are opening and closing 
bool Brackets(char opening, char closing)
{
	if( opening == '(' && closing == ')' ) return true;
	else if ( opening == '[' && closing == ']' ) return true;
	else if ( opening == '{' && closing == '}' ) return true;
	return false;
}

// checks for when 
bool BalancedParentheses(string b)
{
	stack<char> a;
	for(int i = 0; i < b.length(); i++)
	{
		if( b[i] == '(' || b[i] == '{' || b[i] == '[' )
			a.push(b[i]);
		else if( b[i] == '(' || b[i] == '}' || b[i] == ']' )
		{
			if( a.empty() || !Brackets( a.top(), b[i] ) )
				return false;
			else
				a.pop();
		}
	}
	return a.empty();
}

int main()
{
	// tests BalancedParentheses function	
	string c;
	cout << "Enter an expression: ";
	cin >> c;
	if(BalancedParentheses(c))
		cout << "Nice! Balanced!" << endl;
	else
		cout << "Wow...not balanced." << endl;
}


The other issue I'm having is that my professor has changed the assignment (less than 24 hours before it is due...ugh) for us to instead have it open a file that the user enters in, read the file that the user selected, run the code for if it is balanced, and close the file. I'd greatly appreciate code to see how to fix the first problem and add the second problem to the program. Thank you so much for any help you can offer!
For your first issue:
Line 24 should be:
else if (b[i] == ')' || b[i] == '}' || b[i] == ']')
Last edited on
I feel really dumb for not catching that but thank you so much!
Topic archived. No new replies allowed.