【问题标题】:switch statement C++ [default part]switch 语句 C++ [默认部分]
【发布时间】:2015-05-02 09:42:44
【问题描述】:

我正在编写一个关于 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) 范围内时,switch 的默认部分仍然会显示出来。我只想显示我的选择。谁能帮帮我!非常感谢

【问题讨论】:

  • 您好,如果其中一个答案帮助您解决了您的问题,请检查是否正确。如果没有,我们可以尝试进一步帮助您。

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


【解决方案1】:

应该处理回车键'\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;
}

【讨论】:

  • 这种方式解决了我的问题,但循环不起作用。知道怎么做吗?
  • 基本思想阅读\n,忽略。我刚刚通过在默认代码块内移动条件if (choice != '\n') 来更新代码。
【解决方案2】:

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

我认为在这里使用cin.get 没有意义,因为输入23987928 或asdasf 之类的内容会输出大量行...您应该使用cin &gt;&gt; choice 并将您的案例转换为ints .比如:

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

【讨论】:

  • 这会吃掉 any \n。如果您只按 Enter 键,您将在初始方法中收到“无效...”消息。为了避免多余的信息和维持我提到的行为,你应该阅读不需要的\n 和额外的cin.get();
  • @harper 啊,我明白了...但是,添加额外的 cin.get() 只能解决这种情况,并且在每个 case 块中写入 cin.get() 是多余的。我刚刚删除了关于甚至尝试在此实现中使用 cin.get() 的第一部分,因为当您输入 asdasd 或 2374 时,一切仍然中断...
  • @harper 啊,抱歉,已修复。我没有看到他只有五个选择,我很抱歉。尽管如此,使用cin &gt;&gt; 更短,并且增加了可读性..
猜你喜欢
  • 1970-01-01
  • 2012-03-17
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多