Validating infix expresssion (Checking correct brackets)

Greetings to all.
I am writing unit tests for testing the Reverse Polish Notation. The first thing i want to test is to make sure that the expression entered is valid. Apart from testing that there is an operator (/+*-), i want to test for brackets. I want to have something like this

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
#include <iostream>
#include <string>
const char openBrace = '(';
const char closeBrace = ')';

bool hasCorrectBrackets(const std::string &infix)
{
    bool isGoodBracketting = false;
    std::string s(infix);

    for (unsigned int idx = 0; idx < infix.length(); idx++){
	if (infix[idx] == openBrace){ // get corresponding closing brace
		s = infix.substr(idx);
		//std::cout << "1 " << s << std::endl;
		auto closeBra = s.find_first_of(closeBrace);

		if (closeBra != std::string::npos){
			std::string s2 = s.substr(closeBra);
			//std::cout << "2 " << s2 << std::endl;
			isGoodBracketting = true;
		}
	}
    }
	return isGoodBracketting;
}
	
int main()
{
 std::string infix1{"23+4*(3-4)"};  // expect yes
 std::string infix2{"(24-5)+553*(2+2"}; //expected No

  std::cout << (hasCorrectBrackets(infix1)? "yes" : "no") << std::endl;

  std::cout << (hasCorrectBrackets(infix2)? "yes" : "no") << std::endl;

  return 0;
}

Program seem to end when ')' is reached. How do i iterate all cases? Thanks for your help in advance.
Last edited on
This code will fail for expressions with nested brackets: 5 * (4 - (5 + 2) * 4)
Also it'll return false positives if there's at least one correct bracket set before an incorrect one, e.g. infix2 will be a false positive.

Since you're going to iterate through the whole string anyway so why not do this?
1
2
3
4
5
6
7
8
9
10
11
bool hasCorrectBrackets(const std::string &infix) 
{
	int bracketSum = 0;
	for (unsigned int idx = 0; idx < infix.length(); idx++) {
		if (infix[idx] == openBrace) 
			++bracketSum;
		if (infix[idx] == closeBrace)
			--bracketSum;
	}
	return (bracketSum == 0);
}
Last edited on
@Ihatov,
I have tested it with
1
2
3
4
5
6
7
 
"(24-5)+553*(2+2)"     // correct (true)
"5 * (4 - (5 + 2) * 4)" // correct (true)
"(24-5)+553*(2+2"  // correct (false)
"((24-5)+553*(2+2)" // correct (false)
"((24-5)+553*(2+2))" // correct (true)
"((24-5)+(553*(2+2))" // correct (false) 


Thanks. I am not sure i could figure that out. --/++bracketSum is genius.
Topic archived. No new replies allowed.