switch语句C ++ [默认部分]

时间:2015-03-02 05:04:10

标签: c++ visual-studio-2012 while-loop switch-statement default

我正在编写一个关于switch语句的基本程序。菜单有5种选择,如果使用输入无效数字,则应再次提示用户进行选择(范围为1-5)。这是我到目前为止所得到的:

#include <iostream>
#include "Menu.h"
using namespace std;

void Menu::inputChoices()
{
    int choice;

    cout << "IHCC Computer Science Registration Menu" << endl;
    cout << "1. Welome to Computer Programming in C++" << endl;
    cout << "2. Welcome to Java Programming" << endl;
    cout << "3. Welcome to Android Programming" << endl;
    cout << "4. Welcome to iOS Programming" << endl;
    cout << "5. Exit" << endl;
    cout << "\nEnter your selection: " << endl;

    while ((choice = cin.get()) != EOF)
    {
        switch (choice)
        {
        case '1':
            cout << "Welcome to Computer Programming in C++" << endl;
            break;
        case '2':
            cout << "Welcome to Java Programming" << endl;
            break;
        case '3':
            cout << "Welcome to Android Programming" << endl;
            break;
        case '4':
            cout << "Welcome to iOS Programming" << endl;
            break;
        case '5':
            cout << "Exiting program" << endl;
            break;
        default:
            cout << "Invalid input. Re-Enter your selection: " << endl;
        }
    }
}

这个项目有3个文件,这是源文件。我的问题是当我输入一个数字在范围(1-5)时,开关的默认部分仍然显示出来。我只是想出现我的选择。任何人都可以帮助我!非常感谢你

2 个答案:

答案 0 :(得分:2)

您也获得默认值的原因是因为cin.get()正在读取换行符(10)。

我不认为使用cin.get在这里有意义,因为输入23987928asdasf之类的内容会输出大量的行...你应该使用cin >> choice和将您的案例转换为int。类似的东西:

cin >> choice;
switch (choice)
{
    case 1:
        cout << "Welcome to Computer Programming in C++" << endl;
        break;
    // ...
    default:
        cout << "Invalid input. Re-Enter your selection: " << endl;
}

答案 1 :(得分:0)

输入键&#39; \ n&#39;应该处理。请尝试以下操作,看看它是否有效:

while ((choice = cin.get()) != EOF)
{
  case 1:
  // ...
  // Basic idea is read extra `\n` and ignore it. Use below if condition
  default:
        if(choice != '\n')
          cout << "Invalid input. Re-Enter your selection: " << endl;
}