I prefer to read input as strings and then sanitize them with boost::lexical_cast<> :
#include <boost/lexical_cast.hpp> #include <iostream> #include <string> int main () { std::string s; while( std::cin >> s) { try { int i = boost::lexical_cast<int>(s); std::cout << "You entered: " << i << "\n"; } catch(const std::bad_cast&) { std::cout << "Ignoring non-number: " << s << "\n"; } } }
Postscript: if you are allergic to Boost, you can use this lexical_cast implementation:
template <class T, class U> T lexical_cast(const U& u) { T t; std::stringstream s; s << u; s >> t; if( !s ) throw std::bad_cast(); if( s.get() != std::stringstream::traits_type::eof() ) throw std::bad_cast(); return t; }
Robα΅©
source share