在使用cin条件接收输入时按Enter键时出现奇怪的行为

时间:2018-01-04 23:39:15

标签: c++ cin

我有这个代码检查index是否是一个介于1和矢量成员大小之间的整数,名为options_(菜单实现):

int ConsoleMenu::GetSelection() {
int index;
std::cout << "Please enter your selection index. " << std::endl;
while (!(std::cin >> index) || std::cin.get() != '\n' || index < 1 ||    index > options_.size()) {
  std::cout << "Error. index must be a valid integer. Try again: " <<   std::endl;
  std::cin.clear();
  std::cin.ignore(256, '\n');
  }
}

但有时当我输入一个数字然后按回车时,似乎程序无法识别我按下回车键。有人可以帮忙吗? 非常感谢!

1 个答案:

答案 0 :(得分:0)

阅读getline()行,使用std::stringstream解析,并测试它是否符合您的条件:

int ConsoleMenu::GetSelection() {
    std::cout << "Please enter your selection index. " << std::endl;
    while (true) {
        std::string line;
        std::getline(std::cin, line);
        std::stringstream linest(line);
        int index;
        if ((linest >> index) && index >= 1 && index < options_.size()) {
            return index;
        }
        std::cout << "Error. index must be a valid integer. Try again: " <<   std::endl;
    }
}