代码的作用是询问用户他想要哪张卡,并根据选择的卡打印出一条声明。
我的目的是如果输入的数字不是1,2和3,则返回卡选择功能。
还有一个for循环,使该过程可以进行多次。
最好的方法是什么,我该怎么做?
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
cardchoice = CardSelect();
if (cardchoice == 1) {
cout << "You got hearts" << endl;
loop = false;
} else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
loop = false;
} else if (cardchoice == 3) {
cout << "You got joker" << endl;
loop = false;
} else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}
将返回类型更改CardSelect()
为void,因为您只需在该函数中打印一些语句即可:
void CardSelect()
{ // Your cout statements
}
在中调用它main()
,并为cardchoice
变量使用切换大小写。
如果你想保持运行switch语句,直到你得到一个有效的输入,在inifinte循环把所有的东西(如while(1)
由布尔(它集设置为true),并设置退出条件false
开始),使用break
时的条件是在线北京,以摆脱循环:
int main()
{
while(1)
{
bool valid = false;
CardSelect(); // call to your function
int cardchoice;
cin >> cardchoice;
switch(cardchoice)
{
case 1:
cout << "You got hearts" << endl;
valid = true;
break;
case 2:
cout << "You got diamonds" << endl;
valid = true;
break;
case 3:
cout << "You got joker" << endl;
valid = true;
break;
default:
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
break;
} if(valid) break;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句