In C++. Write a program that decides whether a file contains balanced curly brac
ID: 3727350 • Letter: I
Question
In C++.
Write a program that decides whether a file contains balanced curly braces, parentheses, square brackets, and angled brackets. Input the file name, open it, and read one character at a time until end-of-file. If the file is balanced, your program should output "Balanced". If the file is not balanced your program should output "Not Balanced". For example, the following files are balanced This is ftest} file and [your] program should [(ojut)pfuIt] K>] Balanced #include using namespace std; main() int a[ 100]; a[20] ((13 / 2) coutExplanation / Answer
Please find my implementation.
/*
C++ Program to check for balanced parentheses in an expression using stack.
Given an expression as string comprising of opening and closing characters
of parentheses - (), curly braces - {} and square brackets - [] and square brackets - <>
, we need to
check whether symbols are balanced or not.
*/
#include<iostream>
#include<stack>
#include<string>
#include <fstream>
using namespace std;
// Function to check whether two characters are opening
// and closing of same type.
bool ArePair(char opening,char closing)
{
if(opening == '(' && closing == ')') return true;
else if(opening == '{' && closing == '}') return true;
else if(opening == '<' && closing == '>') return true;
else if(opening == '[' && closing == ']') return true;
return false;
}
bool checkBraces(string fileName)
{
char ch;
fstream fin(fileName.c_str(), fstream::in);
stack<char> S;
while(fin >> noskipws >> ch)
{
if(ch == '<'||ch == '(' || ch == '{' || ch == '[')
S.push(ch);
else if(ch == '>' || ch == ')' || ch == '}' || ch == ']')
{
if(S.empty() || !ArePair(S.top(),ch))
return false;
else
S.pop();
}
}
return S.empty() ? true:false;
}
int main()
{
/*Code to test the function AreParanthesesBalanced*/
string fileName;
cout<<"Enter file name: "; // input fileName
cin>>fileName;
if(checkBraces(fileName))
cout<<"Balanced ";
else
cout<<"Not Balanced ";
}