您可以使用通用模板并简化此代码,这些代码将得到优化,更易于阅读。
#include <iostream>
#include <limits>
enum Input1 { Type1 = 1, Type2 = 2, Type3 = 3, Type4 = 4};
enum Input2 { Type11 = 1, Type22 = 2};
bool validate_input(Input1 input1, Input2 input2 = Type11) {
return (input1 >= Type1 && input1 <= Type4) && (input2 == Type11 || input2 == Type22);
}
template <typename T>
T get_valid_input(const std::string& prompt, const std::string& error_message = "Invalid input! Try again.") {
T input;
do {
std::cout << prompt;
std::cin >> input;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} else {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return input;
}
std::cout << error_message << std::endl;
} while (true);
}
int main() {
Input1 eInput1;
Input2 eInput2;
eInput1 = get_valid_input<Input1>("Select option: 1, 2, 3 or 4:", "Invalid input for input1! Must be between 1 and 4.");
eInput2 = get_valid_input<Input2>("Select option: 1 or 2:", "Invalid input for input2! Must be 1 or 2.");
std::cout << "Valid inputs: " << static_cast<int>(eInput1) << ", " << static_cast<int>(eInput2) << std::endl;
return 0;
}