[英]Exit from switch 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
}
我尝试了 break 语句,但是 break 方法不会退出到 main 方法并运行最后一个以下语句。 我还想在案例内部运行方法,这样当玩家选择 1 时,它会显示玩家的余额。 此外,当玩家输入值 2 时,它会显示购买的武器向量。
使用return
而不是break
退出当前的 function。 然后你不需要while (ch != '3')
。 相反,您可以使用无限循环:
while (true) {
// ...
case '3':
cout << " Bye.\n";
return;
}
cin.ignore();
cin.get();
}
您也可以使用for (;;)
而不是while (true)
,但这只是一种风格选择。
另外,不要在 main 的循环中调用PlayerMenu()
。 做就是了:
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. ";
}
break
在此上下文中退出switch
。 如果您想退出function ,则需要return
。
您的PlayerMenu()
function 退出就好了。 问题出在main()
中:
while (z == 0) {
PlayerMenu();
}
循环中没有任何内容可以修改z
,因此它永远不会退出。 它只是永远回到菜单。
我不知道您是打算在那里循环还是只是用if
测试它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.