Welcome to W3Courses
 Like Us on Facebook

Balancing Brackets Source Code in C++

This programs opens a specified file and checks if brakets in that file are balanced or not, good for checking your code.

#include <iostream.h>
#include <fstream.h>
#include <ctype.h>
#include <stdlib.h>
#include <istream.h>

#define SIZE 500

//STACK
template <class Item>
class STACK
{
private:
 struct node
  { Item item; node* next;
   node(Item x, node* t)
   { item = x; next = t;}
  };
 typedef node *link;
 link head, null;

 void deletelist()
 {
  for (link t = head; t != 0; head = t)
  { t = head->next; delete head; }
 }

public:
 STACK()
  { head = 0;}

 STACK(const STACK& rhs)
 { head = 0; *this = rhs;}

 STACK& operator=(const STACK& rhs)
 {
  if (this == &rhs)
   return *this;
  deletelist();
  link t = rhs.head;
  while (t != 0)
  {
   push(t->item);
   t = t->next;
  }
  return *this;
 }
 ~STACK()              //destructor
  {deletelist();}
 
 Item top()
  { return (head->item); }
 STACK nullstack()
  { return (null = 0);}
 int empty_stack(STACK S)
  { return (S == 0);}
 bool empty() const
  { return (head == 0);}
 void push(Item x)
  { head = new node(x, head);}
 Item pop()
  { Item v = head->item; link t = head->next;
  delete head; head = t; return v;}
};


int main()
{
        STACK<char> S;   //stack S

        char a[SIZE]= "0";
        char x;
        int i,check=1;
        char buffer[20];
        ifstream file;        
        cout << "Please Enter File name: ";
        cin >> buffer;
        file.open(buffer);   //opening the file

  do
  { 
   file.getline(a, SIZE);  //reading file line by line
   for(i=0;i<=SIZE;i++)
   {
    x=a[i];
    if(x=='[' || x=='(' || x=='{')
     S.push(x);
    else if(x== '/')
    {
     S.push(x);
     x=a[++i];
     if(x== '*')
      S.push(x);
     else
     {
      check = 0;
      goto end;
     }
    }
    else if(x==']' && S.top()=='[' || x==')' && S.top()=='(' || x=='}' && S.top()=='{' )
     S.pop();
    else if ( S.top()=='*' && x=='*')
    {
     S.pop();
     x=a[++i];
     if(S.top()=='/' && x=='/')
      S.pop();
     else
     {
      check=0;
      goto end;
     }
    }
    else if(S.empty() && (x==']' || x==')' || x=='}' || x=='*'))
    {
     check=0;
     goto end;
    }
    else if(x==']' && S.top()!='[' || x==')' && S.top()!='(' || x=='}' && S.top()!='{' )
    {
     check = 0;
     goto end;
    }
    a[i]= 0;
   }

  }while(!file.eof());

end:
 if(check==0)
  cout<<"Brackets are not balanced."<<endl;
 else
  cout<<"Brackets are balanced."<<endl;

 return 0;
}
 

Share