我有这段代码,它会进行输入检查。它工作到某个时候,但是当我输入例如应该无效的“12rc”时,检查被跳过。我该如何改变它?提前致谢!
cout << "Enter your choice 1, 2, 3: ";
cin >> choice;
cout << endl;
while (cin.fail() || choice <=0 || choice >=4) { // check input value
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Wrong input value! Please enter only 1, 2, 3: ";
cin >> choice;
cout << endl;
最佳答案
我假设您想从标准输入流中获取一个整数。在其他情况下,您可能会采用相同的想法并意识到如何概括您的问题。 我认为它可能会像这样以某种方式解决
#include <iostream>
#include <cctype>
#include <stdexcept>
void skip_to_int() {
if (std::cin.fail()) {
// try to fix up a mess in the input
std::cin.clear();
for (char ch; std::cin >> ch; ) {
if (std::isdigit(ch) || ch == '-') {
std::cin.unget()
return;
}
}
}
// throw an error for example
throw std::invalid_argument{"Not integral input"};
}
int get_int() {
int n;
// try to get the integer number
while (true) {
if (std::cin >> n) {
return n;
}
std::cout << "Sorry, that was not a number. Try again" << std::endl;
// if user inputed not an integral try to search through stream for
// int occurence
skip_to_int();
}
}
int main() {
std::cout << "Enter your choice 1, 2, 3: " << std::endl;
int choice = get_int();
while (choice <= 0 && choice >= 3) {
// continue searching
choice = get_int();
}
// process choice somehow
}
关于C++ 输入检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37274380/