gpt4 book ai didi

c++ - while循环if和else

转载 作者:行者123 更新时间:2023-12-01 14:52:56 29 4
gpt4 key购买 nike

代码的作用是询问用户他想要哪张卡,并根据选择的卡打印出一条声明。

我的目的是如果输入的数字不是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))中,并通过将boolean设置为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;
}
}

关于c++ - while循环if和else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61233990/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com