本文介绍了C ++ 11 cin输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中(即使用C ++ 11技术)验证cin输入的最佳方法是什么?我读了很多其他答案(都涉及cin.ignore,cin.clear等),但是这些方法看起来很笨拙,并导致很多重复的代码.

What is the best way in C++11 (ie. using C++11 techniques) to validate cin input? I've read lots of other answers (all involving cin.ignore, cin.clear, etc.), but those methods seem clumsy and result in lots of duplicated code.

验证"是指既提供了格式正确的输入,又满足了特定于上下文的谓词.

By 'validation', I mean that both well-formed input was provided, and that it satisfies some context-specific predicate.

推荐答案

我正在发布我对解决方案的尝试作为答案,希望它对其他人有用.无需指定谓词,在这种情况下,该功能将仅检查格式正确的输入.我当然愿意接受建议.

I'm posting my attempt at a solution as an answer in the hopes that it is useful to somebody else. It is not necessary to specify a predicate, in which case the function will check only for well-formed input. I am, of course, open to suggestions.

//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;
}

如果有更好的方法,我欢迎您提出建议!

If there's a better approach, I'm open to suggestions!

这篇关于C ++ 11 cin输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:55