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

问题描述 投票:0回答:1

我有这个代码检查索引是否是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');
  }
}

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

c++ cin
1个回答
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.