Write a C++ program that will determine if a string has balanced delimiters. A s
ID: 3762039 • Letter: W
Question
Write a C++ program that will determine if a string has balanced delimiters. A string may use more than one type of delimiter to bracket information into blocks. For example, a string may use braces { }, parentheses ( ), and brackets [ ] as delimiters. A string is properly delimited if each right delimiter is matched with a preceding left delimiter of the same type in such a way that either the resulting blocks of information are disjoint, or one of them is completely nested within the other. Write a program that uses a single stack to check whether a string containing braces, parentheses, and brackets is properly delimited. Use input file string.txt as input to test your program.
Explanation / Answer
}
#include<iostream> #include<stack> #include<string> 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; 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() { /*Code to test the function AreParanthesesBalanced*/ string expression; cout<<"Enter an expression: "; // input expression from STDIN/Console cin>>expression; if(AreParanthesesBalanced(expression)) cout<<"Balanced "; else cout<<"Not Balanced ";}
{ string STRING; ifstream infile; infile.open ("names.txt"); while(!infile.eof) // To get you all the lines. { getline(infile,STRING); // Saves the line in STRING. cout<<STRING; // Prints our STRING. } infile.close(); system ("pause"); } Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.