代码的作用是询问用户他想要哪张卡,并根据选择的卡打印出一条声明。
我的目的是如果输入的数字不是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;
}
}
}
答案 0 :(得分:1)
将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;
}
}
答案 1 :(得分:0)
首先,您要寻找的是continue
,其次,您需要摆脱没有意义的这一行:
cardchoice = CardSelect();
因为它会删除用户输入
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;
if (cardchoice == 1) {
cout << "You got hearts" << endl;
}
else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
}
else if (cardchoice == 3) {
cout << "You got joker" << endl;
}
else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}
答案 2 :(得分:0)
您不应致电cardchoice = CardSelect();
。
此呼叫将用0覆盖cardchoice
。删除此呼叫。
您打印值以查看正在发生的情况。这是学习的好方法。 希望这会有所帮助。