#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 用于弯圆括号countsp
用于s方圆括号countrp
用于圆开括号countcl
用于大括号或最后一个括号开括号
countsl 用于方括号
countrl 用于圆闭括号
例如。输入 {()}
输出平衡
输入 {(}{)}
输出不平衡 它一直工作到第 30 行并打印 equal 之后它给出错误 Segmentation fault (core dumped)