#include #include #include #include #include typedef std::stack Brackets; void pushOpeningBrackets(Brackets& opening, char ch) { if (ch == '{') opening.push('{'); else if (ch == '(') opening.push('('); else if (ch == '[') opening.push('['); } bool errorsFound(Brackets& stack, char openingBracket, char closingBracket) { // unmatched? if (stack.empty()) { std::cerr << "Unmatched " << closingBracket; return true; } char topBracket = stack.top(); stack.pop(); // not a match? if (topBracket != openingBracket) { if (topBracket == '{') std::cerr << "Expected } but found " << closingBracket; else if (topBracket == '(') std::cerr << "Expected ) but found " << closingBracket; else if (topBracket == '[') std::cerr << "Expected ] but found " << closingBracket; return true; } return false; } int main() { std::cout << "Enter a text file name: "; std::string filename; std::getline(std::cin, filename); std::ifstream inFile(filename.c_str(), std::ios::in); if (!inFile) return EXIT_FAILURE; Brackets stack; std::string fileLine; while (inFile >> fileLine) { for (char ch : fileLine) { pushOpeningBrackets(stack, ch); if (ch == '}') { if (errorsFound(stack, '{', '}')) { return EXIT_SUCCESS; } } else if (ch == ')') { if (errorsFound(stack, '(', ')')) { return EXIT_SUCCESS; } } else if (ch == ']') { if (errorsFound(stack, '[', ']')) { return EXIT_SUCCESS; } } } } // checks for missing bracket or full match if (!stack.empty()) { char topBracket = stack.top(); stack.pop(); if ('{' == topBracket) std::cerr << "0"; else if ('(' == topBracket) std::cerr << "0"; else if ('[' == topBracket) std::cerr << "0"; } else std::cout << "1"; }