fork download
  1. #include <iostream>
  2. #include <limits>
  3. #include <cctype>
  4.  
  5. int main()
  6. {
  7. int age;
  8. char c;
  9. while( !( std::cin >> age ) || ( std::cin.get(c) && c != '\n' ) )
  10. {
  11. std::cout << "invalid input, please try another: ";
  12. std::cin.clear(); //clear the bufer
  13. std::cin.ignore( std::numeric_limits<std::streamsize>::max() , '\n' ); //ignore anything that might be left in the buffer
  14. }
  15.  
  16. std::cout << std::endl << std::endl << "You entered: " << age << std::endl;
  17. return 0;
  18. }
Success #stdin #stdout 0s 3344KB
stdin
a1a
a2
3a
4 a
5    
6
stdout
invalid input, please try another: invalid input, please try another: invalid input, please try another: invalid input, please try another: invalid input, please try another: 

You entered: 6