Answer to Question #284475 in C++ for nat

Question #284475

Write a program which reads a C++ source file and checks that all instances of brackets are balanced, that is, each ‘(’ has a matching ‘)’, and similarly for [] and {}, except for when they appear inside comments or strings. A line which contains an unbalanced bracket should be reported by a message such as the following sent to standard output: '{' on line 15 has no matching '}'


1
Expert's answer
2022-01-03T14:25:41-0500
 
include<iostream>
	#include<stack>
	#include<string>
	using namespace std;
	
	bool ArePair(char opening,char closing)
	{
		if(opening == '(' && closing == ')') return true;
		else if(opening == '{' && closing == '}') return true;
		else if(opening == '[' && closing == ']') return true;
		return false;
	}
	bool AreParanthesesBalanced(string exp)
	{
		stack<char>  S;
		for(int i =0;i<exp.length();i++)
		{
			if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
				S.push(exp[i]);
			else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
			{
				if(S.empty() || !ArePair(S.top(),exp[i]))
					return false;
				else
					S.pop();
			}
		}
		return S.empty() ? true:false;
	}
int main()
	{
		
		string expression;
		cout<<"Enter an expression:  "; // input expression from STDIN/Console
		cin>>expression;
		if(AreParanthesesBalanced(expression))
			cout<<"Balanced\n";
		else
			cout<<"Not Balanced\n";
	}



	

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog