Our Feeds

Wednesday, 23 December 2015

AJITH KP

Evaluation of Expression for Bracket Matching in C++

Hi GuyZ,
     Evaluation of Expression for Bracket Matching using C++ is another application of `STACK` data structure. This is another question you may have to solve during your BE/B.Tech/MCA graduation.



Solution

#include <iostream>
#include <vector>
using namespace std;
/*
      Bracket Matching in C++
 Coded By Ajith Kp (C)  http://www.terminalcoders.blogspot.com
*/
template <typename T>
class stack{
 vector<T> v;
public:
 void push(T c){
  v.push_back(c);
 }
 T pop(){
  T top = v.back();
  v.pop_back();
  return top;
 }
 int empty(){
  if(v.empty()){
   return 1;
  }
  return 0;
 }
};
class bracketMatch{
 char str[1024], *ptr;
 stack<char> s;
public:
 void read(){
  cout<<"Enter expression: ";
  cin.getline(str, 1024);
 }
 void check(){
  ptr = str;
  int err = 0;
  char top;
  while(*ptr!='\0'){
   switch(*ptr){
    case '{':
    case '(':
    case '[':
     s.push(*ptr);
     break;
    case '}':
     if(s.empty()){
      err = 2;
     }
     else if((top=s.pop())!='{'){
      err = 1;
     }
     break;
    case ')':
     if(s.empty()){
      err = 2;
     }
     else if((top=s.pop())!='('){
      err = 1;
     }
     break;
    case ']':
     if(s.empty()){
      err = 2;
     }
     else if((top=s.pop())!='['){
      err = 1;
     }
     break;
   }
   if(err==1){
    cout<<"Error: You haven't closed "<<top<<" before "<<*ptr<<endl;
    return;
   }
   else if(err==2){
    cout<<"Error: You haven't opened ";
    if(*ptr==']'){
     cout<<"[";
    }
    else if(*ptr=='}'){
     cout<<"{";
    }
    else if(*ptr==')'){
     cout<<"(";
    }
    cout<<" to close"<<endl;
    return;
   }
   ptr++;
  }
  if(!s.empty()){
   cout<<"Error: You haven't closed ";
   while(!s.empty()){
    cout<<s.pop()<<" ";
   }
   cout<<" correctly"<<endl;
  }
  else{
   cout<<"Success: Your expression is correct"<<endl;
  }
 }
};
int main(){
 bracketMatch bm;
 bm.read();
 bm.check();
}