braces program (logic)

Hi Everyone I am writing a code to check if the braces are balanced, but I am confused on how to eliminate:

1. // {} inside a comment
2. /* {} inside block comment */
3. braces that follow a backslash '\{' or "{", or '}'

Basically I was wondering if there was call function, that I am not familiar.

or a simple way to write code.

Any hint is appreciated
Keep a variable that checks that you are in a valid place for a brace. If it encounters //, it remains false until it reaches \n, if it encounters /*, it remains false until it reaches */, if it encounters \, it remains false for the next char(make sure to allow \\{, when you encounter \, just skip the next char)
Thank you for the quick reply Intrexa.

I am confused on the the last part of your comment. Not sure I know how to do that...

(make sure to allow \\{, when you encounter \, just skip the next char) ?
A easy solution is to use a stack for such stuff. It is easier to visualize and program too.
I have not covered that yet sohguanh
Sohguanh, I was not counting the braces, and for that, I would use a simple integer, no need for a stack. I was just saying how to ignore the 3 special cases.

Detroit, when you check a char, if it is \, immediatly skip the next char. This will handle the 2 cases of \{ and \\{ correctly.
Is it possible to write an output file and display it on the compiler screen at the same time?
Sohguanh, I was not counting the braces, and for that, I would use a simple integer, no need for a stack. I was just saying how to ignore the 3 special cases.


Do you want to just handle the 3 special cases or possibly other more? The more comprehensive solution would be to use Boost RegEx library to help you do such stuff. It is a bit sad Standard C++ does not have any Regular Expression library to help developers out. We have a simple regex in Java libraries though.
What other more cases could their possibly be besides those 3? I'm sure it could be done with regular expressions, but I can only string together fairly basic sequences, what would a regex for the original problem look like?
Don't forget:
1
2
3
4
// This \
is a comment {}
"This \
is a string {}"

EDIT: The site's syntax highlighter broke, but it is valid syntax.
Last edited on
Topic archived. No new replies allowed.