我有这样的事情:
while (!(cin >> num) || (cin.get() != '\n')){
cin.clear();
cin.ignore(100, '\n');
}但是,我无法确定在哪里验证数字在1到10之间,而不导致程序挂起。
发布于 2020-09-29 03:28:57
您可以接受一个std::string,然后使用std::stoi验证输入,如下所示
int getIntInput(int from, int to) {
std::string input;
bool isValidInput = false;
int validinput;
while(!isValidInput) {
try {
std::cout << "\nPlease Enter a valid input between "<< from <<" and " << to <<":\t";
std::cin >> input;
size_t takenChars;
validinput = std::stoi(input, &takenChars);
if (validinput >= from && validinput <= to && takenChars == input.size()) isValidInput = true;
} catch (...) {
}
}
return validinput;
}
int main()
{
std::cout << getIntInput(-3, 2);
}发布于 2020-09-29 04:29:02
int input;
std::cin >> input;
if ("max" > input && input > "min")
{
//what you want to do
}
else{
//error handling
}其中max和min是你设定的两个数字作为你的边界。
https://stackoverflow.com/questions/64112347
复制相似问题