I could not resist making a kind of puzzle version. The task that I set, just for fun, was to write the right program for the task, which in itself is balanced. This largely excludes curly braces in literals like "[" or,
if (A[i] == "(" || A[i] == "{" || A[i] == "["){ a.push(A[i]); }
For fun, I pass the source code through myself, and it returns OK == true. Of course, it works for any file.
Note how reading a file and filtering uninteresting characters is discarded by the get function.
#include <stack> #include <string> #include <fstream> #include <cassert> static std::string chars{ "(){}[]" }; static char get(std::ifstream &in) { char nxt; while (in >> nxt) { if (std::string::npos != chars.find(nxt)) { return nxt; } } return 0; } int main(int argc, char* argv[]) { std::ifstream in(argv[1]); std::stack<char> stk; bool OK = true; for (char nxt = get(in); nxt; nxt = get(in)) { auto pos = chars.find(nxt); if (pos % 2) { if (stk.empty() || stk.top() != chars[pos-1]) { OK = false; break; } else { stk.pop(); } } else { stk.push(nxt); } } return OK; }
source share