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

时间:2018-02-17 06:01:58

标签: c++ loops if-statement switch-statement

我对编程很陌生,正在进行编码挑战http://www.cplusplus.com/forum/articles/12974/。我无法通过谷歌搜索找到我的具体问题的答案,这是我第一次在这里发帖,所以如果我违反了任何指导方针,我会道歉!我正在研究让用户选择一个数字来挑选他们最喜欢的饮料的挑战。

我刚刚了解了switch语句,我命名了5个案例,不包括默认值。我试图弄清楚如何在switch语句中包含if语句(如果这是可能的话),或者它可能是我正在寻找的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;
}

1 个答案:

答案 0 :(得分:0)

  

我试图让它成为如果用户没有输入有效的案例编号并且它变为默认值。 (例如:除1,2,3,4或5以外的任何其他内容)我希望用户在遇到默认情况时再次尝试输入正确的数字。

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

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 );
}