且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++ 11 cin输入验证

更新时间:2023-11-12 12:04:52

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

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!