我有这个代码检查索引是否是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');
}
}
但有时当我输入一个数字并按下输入时,似乎程序无法识别我按下回车键。有人可以帮忙吗?非常感谢!
阅读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;
}
}