Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

P.S: Use any txt file of your choice to test run at the end of the program.. How

ID: 3676977 • Letter: P

Question

P.S: Use any txt file of your choice to test run at the end of the program..

How do I use C++ to ensure that a program has a balanced set of curly braces; that is, for every open curly brace, there is a corresponding close brace. In addition, you should not have a close curly brace without having a corresponding open curly brace first. NOTE: Remember that things in comments should not be considered. The interface for the programming assignment should ask the user to enter a file to check for correctness, after the file is entered, it should display an appropriate message. Then ask the user if they would like to continue.

Explanation / Answer

#include<stack>
#include<string>
#include<iostream>

using namespace std ;

// Ensure that a program has a balanced set of curly braces.
bool braces ( char braceOpened , char braceClosed )
{
   if ( braceOpened =='(' &&braceClosed ==')' ) return true ;
   else if ( braceOpened =='{' &&braceClosed == '}' ) return true ;
   else if ( braceOpened =='[' &&braceClosed == ']' ) return true ;
   return false ;
}
bool bracesesBalancing ( string stmt )
{
   stack< char > Stk ;
   for ( int i = 0 ;i < stmt.length ( ) ; i++ )
   {
       if ( stmt[i] =='(' ||stmt[i] =='{' ||stmt[i] =='[' )
           Stk.push ( stmt[i] ) ;
       else if ( stmt[i] ==')' ||stmt[i] =='}' ||stmt[i] == ']' )
       {
           if ( Stk.empty ( ) ||!braces ( Stk.top ( ) , stmt[i] ) )
               return false ;
           else
               Stk.pop ( ) ;
       }
   }
   return Stk.empty ( ) ? true:false ;
}

int main ( )
{
   /* Logic to check the function is bracesesBalancing */
   string exprssn ;
   cout << " Enter an expressions : " ; // input expressions from STDIN / Console
   cin >> exprssn ;
   if ( bracesesBalancing ( exprssn ) )
       cout << " Balanced " ;
   else
       cout << " It isn't Balanced " ;
}