gpt4 book ai didi

c++ - 如何在 switch 语句内部或外部使用 if 语句 (C++)

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:33 25 4
gpt4 key购买 nike

我是编程新手,正在做从这里找到的编码挑战 http://www.cplusplus.com/forum/articles/12974/ .我无法通过谷歌搜索找到我的具体问题的答案,这是我第一次在这里发帖,所以如果我违反了任何准则,我深表歉意!我正在研究让用户选择一个数字来选择他们最喜欢的饮料的挑战。

我刚刚了解了 switch 语句,我命名了 5 个案例,不包括默认情况。我试图弄清楚如何将 if 语句合并到 switch 语句中(如果这可能的话),或者它可能是我正在寻找的 for 循环?我不确定,但我愿意了解它是什么。我正在尝试这样做,以便如果用户没有输入有效的案例编号并且它将变为默认值。 (例如:1、2、3、4 或 5 以外的任何数字)我希望用户在遇到默认大小写时再次尝试输入正确的数字。

这是我的代码

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
int choice;

cout << "Choose your beverage of choice by number: " << endl;
cout << "1. Coke" << endl;
cout << "2. Dr. Pepper" << endl;
cout << "3. Sprite" << endl;
cout << "4. Iced Tea" << endl;
cout << "5. Water" << endl;
cout << '\n';
cin >> choice;
cout << '\n' << "Choice entered: " << choice << endl;
cout << '\n';
switch (choice)
{
case 1 : cout << "You have chosen Coke." << endl;
break;
case 2 : cout << "You have chosen Dr. Pepper." << endl;
break;
case 3 : cout << "You have chosen Sprite." << endl;
break;
case 4 : cout << "You have chosen Iced Tea." << endl;
break;
case 5: cout << "You have chosen Water." << endl;
break;
default:
cout << "Error. Choice Not valid. Money returned." << endl;
break;

}

system("pause");
return 0;
}

最佳答案

I am trying to make it so that if the user does not enter a valid case number and it goes to default. (ex: anything other than 1, 2, 3, 4, or 5) I want the user to make another attempt at entering a correct number when it hits the default case.

实现这一点的一种方法是在接收用户输入和 switch 语句的代码块周围放置一个 do-while 循环。

int main()
{
bool isValidChoice = true;
do
{
// Reset when the loop is run more than once.
isValidChoice = true;

int choice;

cout << "Choose your beverage of choice by number: " << endl;
cout << "1. Coke" << endl;
cout << "2. Dr. Pepper" << endl;
cout << "3. Sprite" << endl;
cout << "4. Iced Tea" << endl;
cout << "5. Water" << endl;
cout << '\n';
cin >> choice;
cout << '\n' << "Choice entered: " << choice << endl;
cout << '\n';
switch (choice)
{
case 1 :
cout << "You have chosen Coke." << endl;
break;

case 2 :
cout << "You have chosen Dr. Pepper." << endl;
break;

case 3 :
cout << "You have chosen Sprite." << endl;
break;

case 4 :
cout << "You have chosen Iced Tea." << endl;
break;

case 5:
cout << "You have chosen Water." << endl;
break;

default:
cout << "Error. Choice Not valid. Money returned." << endl;
isValidChoice = false;
break;
}
} while ( !isValidChoice );
}

关于c++ - 如何在 switch 语句内部或外部使用 if 语句 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48838416/

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