从开关C ++退出

1 c++

#include <iostream>
#include <string>
#include <vector>
#include "Player.h"
using namespace std;

void PlayerMenu();


int main() {


    int z;
    cout << "Please press 0 to see the PLayers Menu. " << endl;
    cin >> z;
    while (z == 0) {
        PlayerMenu();

    }

    cout << " Now You're Functional Lets get started. ";


};
void PlayerMenu()
{
    char ch;
    int num;

    do {
        system("cls");
        cout << "\n\n\n\t Player Menu";
        cout << "\n\n1 Wallet Balance  ";
        cout << "\n\n2 Player Invetory";
        cout << "\n\n3 To Exit";
        cin >> ch;
        system("cls");
        switch (ch)
        {
        case '1':
            cout << "Your Balance at the moment is ..."<<endl;
            cout << "\n";
            Bank();
            break;

            //Show Wallet Balance
        case '2':

            cout << "Here is your Inventory"<<endl;
            cout << "\n";
            break;

            //Show Inventory

        case '3':
            cout << " Bye.\n";
            break;
            //exit i'VE TRIED bREKA BUT it will not go back to the main source code or main method
        }

        cin.ignore();
        cin.get();


    } while (ch != '3');//If not 1 or 2 or 3 will ignore it
}
Run Code Online (Sandbox Code Playgroud)

我尝试了break语句,但是break方法不会退出到main方法并运行最后的以下语句。我还要在案例中运行方法,以便当玩家选择1时将显示玩家的余额。同样,当玩家输入值2时,它将显示购买武器的向量。

Nik*_* C. 5

使用return代替break退出当前功能。然后,您就不需要了while (ch != '3')。相反,您可以使用无限循环:

while (true) {
    // ...

    case '3':
        cout << " Bye.\n";
        return;
    }

    cin.ignore();
    cin.get();
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用for (;;)代替while (true),但这只是样式选择。

另外,不要PlayerMenu()在main中循环调用。做就是了:

int main()
{
    int z;
    cout << "Please press 0 to see the PLayers Menu. " << endl;
    cin >> z;
    if (z == 0) {
        PlayerMenu();
    }

    cout << " Now You're Functional Lets get started. ";
}
Run Code Online (Sandbox Code Playgroud)