我有一个我确定是一个简单的问题,但我无法理解。在下面的代码中,我希望能够让案例5在之后重新显示选项。我怎样才能做到这一点?提前谢谢!
// Input the race of your character
cout << "Choose a race here: " << endl
<< "1) Human, 2) Elf, 3) Dark Dwarf, 4) Commoner, 5) Race info, 6) Admin Debug Race : ";
cin >> mCharRace;
switch (mCharRace)
{
case 1:
cout << "You have chosen Human!" << endl;
mExpPoints = 999;
mArmor = mArmor + 2;
break;
case 2:
cout << "You have chosen Elf!" << endl;
mAccuracy = mAccuracy + 2;
mWeapon.mDamageRange.mLow = mWeapon.mDamageRange.mLow + 1;
break;
case 3:
cout << "You have chosen Dark Dwarf!" << endl;
mWeapon.mDamageRange.mHigh = mWeapon.mDamageRange.mHigh + 2;
mMaxHitPoints = mMaxHitPoints + 3;
break;
case 4:
cout << "You have chosen Commoner! Brave man." << endl;
mAccuracy = mAccuracy - 3;
mHitPoints = mHitPoints - 5;
mMaxHitPoints = 8;
mExpPoints = -250;
mNextLevelExp = 1500;
mArmor = -1;
break;
case 5:
cout << "Placeholder for explanation text." << endl;
break;
case 6:
cout << "ADMIN POWERS UNITE!!!!!!!" << endl;
mAccuracy = 20;
mHitPoints = 1000;
mMaxHitPoints = 1000;
mExpPoints = 0;
mNextLevelExp = 1000;
mArmor = 100;
mWeapon.mName = "Admin Sword of HNNNG!";
mWeapon.mDamageRange.mLow = 100;
mWeapon.mDamageRange.mHigh = 150;
mGold = 1000000;
break;
答案 0 :(得分:10)
switch-case构造不是迭代构造。它只能选择某个案例并执行它。由于它,控制流程无法恢复。
所以,你不能用它来循环。 将其包装在而或用于循环结构中。
while(condition){
switch (mCharRace){
...
...
}
}
如果要停止循环,只需将条件转为 false 即可。
答案 1 :(得分:6)
将输入和切换代码包装在循环中,并指定变量exitLoop
以退出循环。默认情况下,将该变量设置为TRUE,除非您要重复输入。在那些中,将exitLoop
设置为false。
答案 2 :(得分:1)
在第一个cout之前添加标签
label:
cout << "Choose a race here: " << endl
<< "1) Human, 2) Elf, 3) Dark Dwarf, 4) Commoner, 5) Race info, 6) Admin Debug Race : ";
cin >> mCharRace;
...
然后在案例5中添加
goto label;
答案 3 :(得分:1)
将其置于for(;;)
循环内,并使用continue
代替break
。在break
语句结束后添加另一个switch
来捕获真正想要破解的案例:
for (;;)
{
switch (x)
{
case case_that_wants_to_loop:
// ...
continue;
case case_that_wants_to_break:
// ...
break;
}
break;
}