120k views
5 votes
Write a program that prompts for a file name and then reads the file to check for balanced curly braces, {; parentheses, (); and square brackets, []. Use a stack to store the most recent unmatched left symbol. The program should ignore any character that is not a parenthesis, curly brace, or square bracket. Note that proper nesting is required. For instance, [a(b]c) is invalid

User Orokusaki
by
5.1k points

1 Answer

2 votes

Answer: C++

Step-by-step explanation:

#include<bits/stdc++.h>

using namespace std;

// function to confirm if paranthesis are balanced

bool areParanthesisBalanced(string expr)

{

stack<char> s;

char x;

// Traversing the Expression

for (int i=0; i<expr.length(); i++)

{

if (expr[i]=='('||expr[i]=='['||expr[i]=='{')

{

// Push the element in the stack

s.push(expr[i]);

continue;

}

// IF current current character does not opening

// bracket, then it must be closing. So stack

// cannot be empty at this point.

if (s.empty())

return false;

switch (expr[i])

{

case ')':

// Reserve the top element in a

x = s.top();

s.pop();

if (x=='' ':

// Reserve the top element in b

x = s.top();

s.pop();

if (x=='(' || x=='[')

return false;

break;

case ']':

// Reserve the top element in c

x = s.top();

s.pop();

if (x =='(' || x == '{')

return false;

break;

}

}

// Check Empty Stack

return (s.empty());

}

// Driver program to test above function

int main()

{

cout<<"Enter the file name\\";

char filename[20];

cin>>filename;

ifstream file; //using input stream to read the contents of the file

file.open(filename);

char ch;

string s="";

while (file >> ch) { //reading the content from file char by char

s=s+ch; //storing the content in the string s

}

if (areParanthesisBalanced(s))

cout << "Balanced";

else

cout << "Not Balanced";

return 0;

User Tukan
by
5.8k points