2

我有一个我确定是一个简单的问题,但我无法弄清楚。在下面的代码中,我希望能够让案例 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;
4

4 回答 4

11

switch-case 构造不是迭代构造。它只能选择某个案例并执行它。因此,控制流无法恢复。

所以,你不能用它来循环。将其包装在whilefor循环构造中。

while(condition){
   switch (mCharRace){
   ...
   ...
   }
}

当您想停止循环时,只需将条件设置为false 。

于 2012-10-26T15:00:50.863 回答
6

将输入和切换代码包装在一个循环中,并分配一个变量exitLoop以退出循环。默认情况下将该变量设置为 TRUE,除非在您想要重复输入的情况下。在那些中,设置exitLoop为 false。

于 2012-10-26T15:00:24.283 回答
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;
于 2012-10-26T15:00:15.643 回答
1

将它放在一个for(;;)循环中并使用continue而不是break. break在语句结束后放置另一个switch以捕获真正想要中断的情况:

for (;;)
{
    switch (x)
    {
    case case_that_wants_to_loop:
        // ...
        continue;
    case case_that_wants_to_break:
        // ...
        break;
    }
    break;
}
于 2018-02-28T02:45:55.440 回答