Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 24 additions & 27 deletions Cpp/Parentheses_Checker.cpp
Original file line number Diff line number Diff line change
@@ -1,52 +1,49 @@
// parentheses_checker.cpp
// Compile with: g++ -std=c++17 parentheses_checker.cpp -o parentheses_checker
// A simple program to check whether the parentheses/brackets/braces
// in each input line are balanced.
// Compile: g++ -std=c++17 parentheses_checker.cpp -o parentheses_checker

#include <bits/stdc++.h>
#include <iostream>
#include <stack>
#include <string>
using namespace std;

// Function to check if two brackets are a matching pair
bool isMatching(char open, char close) {
return (open == '(' && close == ')')
|| (open == '[' && close == ']')
|| (open == '{' && close == '}');
return (open == '(' && close == ')') ||
(open == '[' && close == ']') ||
(open == '{' && close == '}');
}

// Function that checks if parentheses in a string are balanced
bool areParenthesesBalanced(const string &s) {
stack<char> st;
for (char ch : s) {
if (ch == '(' || ch == '[' || ch == '{') {
st.push(ch);
} else if (ch == ')' || ch == ']' || ch == '}') {
if (st.empty() || !isMatching(st.top(), ch)) {
return false; // closing bracket without matching opening
}
if (st.empty() || !isMatching(st.top(), ch))
return false; // unmatched closing bracket
st.pop();
}
// ignore other characters
}
// Ignore non-bracket characters
}
return st.empty(); // balanced iff nothing left unmatched
return st.empty(); // Balanced if stack is empty at the end
}

int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);

cout << "Enter string to check (single line). Press Ctrl+D/Ctrl+Z to end:\n";
string line;
// Read whole line (including spaces). For multiple tests, loop or read until EOF.
if (!getline(cin, line)) return 0;

bool balanced = areParenthesesBalanced(line);
if (balanced) cout << "Balanced\n";
else cout << "Not Balanced\n";
cout << "Enter multiple lines to check parentheses balance.\n";
cout << "Press Ctrl+D (Linux/Mac) or Ctrl+Z (Windows) to finish input.\n\n";

// Example quick tests (uncomment to run built-in tests)
/*
vector<string> tests = {
"()[]{}", "([{}])", "(]", "([)]", "a + (b - c) * {d / [e + f]}"
};
for (auto &t : tests) {
cout << t << " -> " << (areParenthesesBalanced(t) ? "Balanced" : "Not Balanced") << '\n';
string line;
// Read multiple lines until EOF
while (getline(cin, line)) {
bool balanced = areParenthesesBalanced(line);
cout << (balanced ? "Balanced" : "Not Balanced") << '\n';
}
*/

return 0;
}