double checkInput() {
double add;
cout << "\n" << endl;
cin >> add;
if (cin.fail()==true)
{
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Incorrect input"<<endl;
}
else
{
return add;
}
}
我使用这段代码来过滤掉字符输入,例如“Blarg”、“bat12cat”和类似的输入,其中字符/字母排在第一位,但是当我测试“1gold”、“0.05cake”等数字排在第一位时然后是字母,程序接受所有数字,直到字母的第一个实例。
我的理解是导致问题并允许数字通过的是 cin.ignore()。
什么会让像“0.05Cats”这样的输入被完全忽略/跳过? 网上查了一下,有人建议用getline()和stringstream。
谢谢。
最佳答案
当您输入类似 1.5dog
的内容然后使用 cin >> some_double;
>>>
将提取一个 double 直到它不能再读了。所以 some_double
获得 1.5 而 dog
仍在流中。这不是故障,因此未设置故障位。由于未设置,您跳过 if 语句并返回 double 值,而其余输入保留在流中,并且会在您下次尝试从流中读取时导致问题。我的建议是改变你阅读输入的方式。您可以通过 std::string
接收输入,然后将其转换为所需的类型。然后,如果转换失败,您可以发出失败信号。我会使用类似的东西:
bool read_double(std::istream & is, double & number)
{
std::string line;
getline(is, line);
std::size_t pos = 0;
double temp = stod(line, &pos);
if (pos != line.size()) // there is extra content in the streams
return false;
number = temp;
return true;
}
你可以看到它与这个 Live Example 一起工作
关于c++ - 某些测试的输入验证未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31924885/