如何在开关语句(C )内或外部使用IF语句

How can I use an if statement within or outside of a switch statement (C++)

本文关键字:语句 外部 IF 开关      更新时间:2023-10-16

我是编程的全新,并且正在从此处发现的编码挑战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 );
}