C ++ 11(即使用C ++ 11技术)验证cin输入的最佳方法是什么?我已经阅读了很多其他答案(全部涉及cin.ignore,cin.clear等),但这些方法看起来很笨拙,导致大量重复的代码。
编辑:通过'验证',我的意思是提供了格式良好的输入,并且它满足某些特定于上下文的谓词。
答案 0 :(得分:1)
我将解决方案的尝试作为答案发布,希望对其他人有用。没有必要指定谓词,在这种情况下,函数将只检查格式良好的输入。我当然愿意接受建议。
//Could use boost's lexical_cast, but that throws an exception on error,
//rather than taking a reference and returning false.
template<class T>
bool lexical_cast(T& result, const std::string &str) {
std::stringstream s(str);
return (s >> result && s.rdbuf()->in_avail() == 0);
}
template<class T, class U>
T promptValidated(const std::string &message, std::function<bool(U)> condition = [](...) { return true; })
{
T input;
std::string buf;
while (!(std::cout << message, std::getline(std::cin, buf) && lexical_cast<T>(input, buf) && condition(input))) {
if(std::cin.eof())
throw std::runtime_error("End of file reached!");
}
return input;
}
以下是其用法示例:
int main(int argc, char *argv[])
{
double num = promptValidated<double, double>("Enter any number: ");
cout << "The number is " << num << endl << endl;
int odd = promptValidated<int, int>("Enter an odd number: ", [](int i) { return i % 2 == 1; });
cout << "The odd number is " << odd << endl << endl;
return 0;
}
如果有更好的方法,我愿意接受建议!
答案 1 :(得分:0)
如果通过验证,您的意思是当您想要int
时想知道是否确实输入了int
,那么只需将输入置于if
条件:
int num;
while (!(std::cin >> num))
{
std::cout << "Whatever you entered, it wasn't an integer\n";
}
std::cout << "You entered the integer " << num << '\n';