Problem:

Given a text file, your program will determine if all the parentheses, curly braces, and square brackets match, and are nested appropriately. Your program should work for mathematical formulas and computer programs.

Your program should read in the characters from the file, but ignore all characters except for the following: { } ( ) [ ]

Your program should use the IntStack implementation (IntStack.h and IntStack.cpp, which will be available from the class webpage).

The general algorithm is to use the stack to store the opening unmatched brackets. When a closing bracket is encountered, check it against the one on top of the stack (pop it off)--make sure it matches. When you are finished there should be no unmatched brackets left on the stack.

Input/Output:

Your program should prompt the user to enter a filename. It should then try to open the file and then check it make sure the brackets all match appropriately. If they all match, the program should output a message saying so. If not, the program should output an appropriate error message.

There are three types of errors that can happen (and they can happen with any kind of bracket):

  • missing } : if you reach the end of the file, and there is an opening { that was never matched, like: int main () { x[size]=10;
  • expected } but found ) : this is a wrong closing bracket, like: {x[i]=10;)...
  • unmatched } : this occurs if there is a closing bracket but not an opening bracket (not even one of the wrong kind), like: int main () { x[i]=10; } }...

NOTES:

  • As soon as you encounter an error, your program should stop and print out the appropriate error message. Do NOT try to keep going and find more errors!
  • The stack is an int stack but you will probably want to put characters on the stack. You can push a character directly on the int stack (it will automatically be converted to an int). When you pop I recommend popping into a char variable first (this will automatically convert the int back into a character).
  • It might be easier to store the expected closing character on the stack when an opening bracket is encountered. This simplifies the matching when a closing bracket is encountered.
  • Beware of stack underflow! Do NOT try to pop an empty stack!
Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.