c++ - C++11 cin input validation -
what best way in c++11 (ie. using c++11 techniques) validate cin input? i've read lots of other answers (all involving cin.ignore, cin.clear, etc.), methods seem clumsy , result in lots of duplicated code.
edit: 'validation', mean both well-formed input provided, , satisfies context-specific predicate.
i'm posting attempt @ solution answer in hopes useful else. not necessary specify predicate, in case function check well-formed input. am, of course, open suggestions.
//could use boost's lexical_cast, throws exception on error, //rather taking reference , 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; }
here's example of usage:
int main(int argc, char *argv[]) { double num = promptvalidated<double, double>("enter number: "); cout << "the number " << num << endl << endl; int odd = promptvalidated<int, int>("enter odd number: ", [](int i) { return % 2 == 1; }); cout << "the odd number " << odd << endl << endl; return 0; }
if there's better approach, i'm open suggestions!
Comments
Post a Comment