2015-03-02 50 views
1

我在写关于switch语句的基本程序。 5个选项菜单,如果使用输入无效号码,应再次提示用户进行选择(范围从1-5)。在这里我得到了什么至今:switch语句C++ [默认部分]

#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)的范围内,开关的默认部分仍然显示。我只想显示我的选择。任何人都可以帮助我!非常感谢您

+0

你好,如果其中一个答案帮助你解决了你的问题,请检查它是否正确。如果没有,我们可以尝试进一步帮助你。 – usandfriends 2015-05-29 00:59:22

回答

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; 
} 
+0

这将吃任何*'\ n'。如果您单独按下Enter键,则会出现初始方法的“无效...”消息。为了避免超级消息*和*维持我提到的行为,应该使用额外的'cin.get();' – harper 2015-03-02 07:38:59

+0

@harper啊读取不需要的'\ n',我看到...但是,添加额外的'cin .get()'只会修复这种情况,在每个case块中写入'cin.get()'都是多余的。我只是删除了第一部分,甚至试图在这个实现中使用'cin.get()',因为当你输入'asdasd'或'2374'时,所有东西都会中断... – usandfriends 2015-03-02 16:26:49

+0

@harper啊,对不起,修好了。我没有看到他只有五个选择,我的歉意。尽管如此,使用'cin >>'更短,并增加了可读性。 – usandfriends 2015-03-02 16:55:50

0

应该处理回车键'\ n'。尝试下面,看看它的工作原理:

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; 
} 
+0

这种方式解决了我的问题,但循环不起作用。任何想法如何? – 2015-03-03 01:49:29

+0

基本思想被读为'\ n'并忽略它。我只是通过在默认代码块内移动条件if(choice!='\ n')来更新代码。 – vcp 2015-03-03 09:56:46