cin >> num;
while (cin.fail() || num < 0 || num > 999999) // child proofing
{
cout << " ERROR: wrong/invalid input try again ";
cin.clear(); // reset any flag errors in the cin
cin.ignore(INT_MAX, '\n');
cin >> num;
}如果我输入整数和字母的组合,它将忽略字母并输入数字
Input: 1234ekl
Output: 1234
Input: 12wr43
Output: 12我需要一种方法来检查输入,以便我可以作为一个有效的情况下,它不是。
发布于 2021-01-26 16:27:41
operator>>会立即解析输入数据,您无法对此进行干预。但是,您可以扫描整个输入行并检查任何非法字符,如下所示:
std::string str;
// scans the entire line
std::getline(std::cin, str);
// checks for existence of any invalid characters
// refer to http://www.cplusplus.com/reference/string/string/find_first_not_of/
if(str.find_first_not_of("0123456789") != std::string::npos) {
[handle the error]
}
// parse the string when you know it is valid
else {
int result = std::stoi(str);
}编辑:正如评论中所建议的,这里有一种替代方法,它使用选项来检索从std::stoi解析的字符数。
std::string str;
std::size_t sz;
int i;
std::getline(std::cin, str);
try {
i = std::stoi(str, &sz);
}
catch(std::exception) {
// failed to parse
[handle the error]
}
if(sz != str.length()) {
// parsed, but there are trailing invalid characters
[handle the error]
}
else {
// valid input was provided
}https://stackoverflow.com/questions/65897857
复制相似问题