#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;
}
}
}
ブラケットのバランスをとろうとしています。入力には、中括弧、丸括弧、および角括弧が含まれます。このコードで何が間違っていたのかを見つけようとしています。私はC ++が初めてで、学ぼうとしています。
説明
countcp中開き括弧用countcp四角開き括弧用countsp
丸開き括弧用countrp中括弧
または最後の開き括弧用
countcl countsl四角
閉じ括弧用countrl
丸い閉じ括弧
用 入力 {()}
出力のバランス
入力 {(}{)}
出力のバランスが取れていない 30 行目までは機能し、その後は等しいと出力され、エラーが発生します セグメンテーション違反 (コア ダンプ)