我對C++的經驗非常有限,我想從代碼中替換「goto」構造。對於重構過於替換goto聲明
int main()
{
int count;
int countSub = 0;
int userCount = 0;
int roleCount = 0;
int parentGroup;
cout<<"enter a number of parentGroup"<< endl;
cin>> parentGroup;
int subGroup;
cout<<"enter a number sub Group"<< endl;
cin>> subGroup;
int rolePerGroup;
cout<<"enter a number role per Sub Group"<< endl;
cin>> rolePerGroup;
int userPerGroup;
cout<<"enter a number user per Role"<< endl;
cin>> userPerGroup;
do
{
if (parentGroup == 0)
{
cout<<"Error"<<endl;
exit(EXIT_FAILURE);
}
else
{
for(count=1;count <= parentGroup; count ++)
{
do
{
if(subGroup == 0) goto hello;
else
{
for(countSub = 1;countSub<=subGroup; countSub ++)
{
do
{
hello:
if (rolePerGroup == 0)
{
cout<<"Error"<<endl;
exit(EXIT_FAILURE);
}
else
{
for(roleCount = 1; roleCount<=rolePerGroup; roleCount ++)
{
do
{
if(userPerGroup == 0) goto print;
else
{
for(userCount = 1; userCount<=userPerGroup; userCount ++)
{
print:
cout<<"Parent groups are: "<< count <<" | "<<"Sub group are : "<<countSub<<" | "<<"Role per Sub group are : "<< roleCount <<" | "<<"User per role are : "<< userCount <<endl;
}}
userCount --;
}while(userCount < 0);
}}
roleCount --;
}while(roleCount < 0);
}}
countSub --;
}while(countSub < 0);
}}
count --;
}while(count < 0);
}
我的第一個建議是這個分裂成多個功能。這就是6個嵌套for循環? – Borgleader
創建打印中正在執行的任何功能,並調用該函數而不是「goto」。 –
if(userPerGroup == 0)轉到打印; –