#include<iostream>
#include<string>
using namespace std;
main()
{
int i, j=0, perlen, countcp=0, countsp=0, countrp=0, countcl=0, countsl=0, countrl=0;
string str, str1;
cout<<"Please enter string"<<endl;
getline(cin, str);
perlen=(str.length())/2;
for(i=0; i<str.length(); i++)
{
if(str[i]=='{')
countcp++;
if(str[i]=='[')
countsp++;
if(str[i]=='(')
countrp++;
if(str[i]=='}')
countcl++;
if(str[i]==']')
countsl++;
if(str[i]==')')
countrl++;
}
str1=str;
if(countcp==countcl and countsp==countsl and countrp==countrl)
{
cout<<"equal"<<endl;
int countwhile=0, j=0;
while(!str.length()==0)
{
if(str[j]=='{' and str[j+1]=='}')
{
str.erase(i, 2);
countwhile++;
}
else if(str[j]=='(' and str[j+1]==')')
{
str.erase(i, 2);
countwhile++;
}
else if(str[j]=='[' and str[j+1]==']')
{
str.erase(i, 2);
countwhile++;
}
if(countwhile>perlen)
{
countwhile=1;
cout<<"reached break"<<endl;
break;
}
j++;
}
if(countwhile==1)
{
cout<<"Balanced string "<<str1<<endl;
}
}
}
i am trying to balance brackets. input will include curly, round and square brackets. i am trying to find what i did wrong in this code. i am new to c++ and i am trying to learn.
explanation
countcp for curly open brackets
countsp for square open brackets
countrp for round open brackets
countcl for curly close or last bracket open brackets
countsl for square close brackets
countrl for round close brackets
eg. input {()}
output balanced
input {(}{)}
output not balanced
it works till line 30 and prints equal after that it gives error Segmentation fault (core dumped)