如何在开关语句(C )内或外部使用IF语句
How can I use an if statement within or outside of a switch statement (C++)
我是编程的全新,并且正在从此处发现的编码挑战http://www.cplusplus.com/forum/articles/12974/。我无法通过Google搜索找到我特定问题的答案,这是我第一次在此处发布,因此,如果我违反了任何准则,我深表歉意!我正在考虑挑战,这使用户选择一个数字来选择他们喜欢的饮料。
我刚刚了解了Switch语句,我命名了5个案例,不包括默认值。我试图弄清楚如何在开关语句中(如果可能的话(中合并IF语句,或者也许是我正在寻找的循环?我不确定,但我愿意了解它的一切。我正在尝试做到这一点,以便用户不输入有效的案例号,并且默认为默认值。(例如:除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;
}
我正在尝试做到这一点,以便如果用户不输入有效的案例号,并且将默认为默认值。(例如:除1、2、3、4或5之外的任何内容(我希望用户在击中默认情况时再次尝试输入正确的数字。
实现这一目标的一种方法是在接收用户输入和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 );
}
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- 在函数内部的声明中初始化数组,并在外部使用它
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 使外部项目可用于find_package CMake
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 如何在开关语句(C )内或外部使用IF语句
- C# 读取完全锁定的文本文件或读取 if 语句外部的输出
- 如何访问在 if 语句内、外部创建的指针
- 包括外部包括警卫的语句
- C++ 嵌套'if'语句中的所有代码都会运行,即使这会更改外部语句的布尔值?
- C++字符串在if语句外部消失
- 重构大型事例语句、外部语句、静态局部语句
- 如何使用 break 语句停止内部和外部循环