/* * ----------------------------------------------------- * CS2S03/SE2S03, October 2011 * Assignment 3, Question 1 * File: PE0408.cpp * ----------------------------------------------------- * This program checks if the bracketing operators * (parantheses, brackets, and curly braces) in a string * are properly nested. * ----------------------------------------------------- */ #include "genlib.h" #include "simpio.h" #include "stack.h" #include /* Private function prototypes */ bool isOpenOp(char op); bool isCloseOp(char op); char CompanionOf(char op); void CheckBracketing(string s); /* Main program */ int main() { string s; cout << "Enter a line to check: "; s = GetLine(); CheckBracketing(s); return 0; } /* * Function: isOpenOp * Usage: if (isOpenOp(op)) ... * ----------------------------------------------------- * This function returns true if op is an open operator. */ bool isOpenOp(char op) { return (op == '(') || (op == '{') || (op == '['); } /* * Function: isCloseOp * Usage: if (isCloseOp(op)) ... * ----------------------------------------------------- * This function returns true if op is a close operator. */ bool isCloseOp(char op) { return (op == ')') || (op == '}') || (op == ']'); } /* * Function: CompanionOf * Usage: c = CompanionOf(op) * --------------------------------------------------- * This function returns the companion operator of op. */ char CompanionOf(char op) { switch(op) { case ')': return '('; case '}': return '{'; case ']': return '['; case '(': return ')'; case '{': return '}'; case '[': return ']'; default: return NULL; } } /* * Function: CheckBracketing * Usage: CheckBracketing(s) * ------------------------------------------------ * This function checks if the bracketing operators * (parantheses, brackets, and curly braces) in s * are properly nested. */ void CheckBracketing(string s) { Stack openOps; for (int i = 0; i < s.length(); i++) { if (isOpenOp(s[i])) { openOps.push(s[i]); } else if (isCloseOp(s[i])) { if (openOps.isEmpty()) { cout << "An close " << s[i] << " comes before an open "; cout << CompanionOf(s[i]) << endl; return; } if (CompanionOf(s[i]) != openOps.pop()) { cout << "The bracketing operators are improperly nested."; return; } } } // end of string is reached if (!openOps.isEmpty()) { cout << "The line is missing "; while (!openOps.isEmpty()) { cout << CompanionOf(openOps.pop()) << " "; } cout << endl; } else { cout << "Bracketing operators are properly nested."; } return; }