【问题标题】:C++ Menu stuck in infinite if user enters invalid integer [duplicate]如果用户输入无效整数,C++ 菜单会卡在无限 [重复]
【发布时间】:2016-10-25 18:56:22
【问题描述】:

我有一个带有可选菜单选项的简单 C++ 菜单。如果用户键入的不是有效的int,例如chardouble,程序将进入无限循环。我的代码如下。

#include <iostream>

using namespace std;

int main()
{
    int selection;
    do  {
        cout << "1) Update inventory" << endl;
        cout << "2) Sell items" << endl;
        cout << "3) List inventory" << endl;
        cout << "4) Quit" << endl;

        cout << "Please select an option: ";
        cin >> selection;
    }
    while (selection != 4);

    return 0;
}

为什么无效响应会导致死循环,如何防止?

【问题讨论】:

标签: c++ menu user-input infinite-loop


【解决方案1】:

之前

cin >> selection;

放置这两行:

cin.clear ();
cin.ignore ();

这将清除缓冲区并允许输入。

【讨论】:

  • 这不是他要问的。他在询问无效输入,例如输入字符而不是数字
  • 我意识到了。这将解决问题。但@jaggedSpire 是对的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
相关资源
最近更新 更多