fork download
  1. #include <iostream>
  2. #include <limits> //numeric_limits
  3.  
  4. int main()
  5. {
  6. int Size;
  7. char c;
  8. std::cout << "Please enter an integer: ";
  9. while( !(std::cin >> Size) || ( std::cin.get(c) && c != '\n' ) )
  10. {
  11. std::cin.clear(); //clear error flags
  12. std::cin.ignore( std::numeric_limits<std::streamsize>::max() , '\n' ); //ignore anything left
  13. //std::cin.ignore( 1024 , '\n' ) or anything large will work too
  14. std::cout << "Invalid input. Please try again(integer only): ";
  15. }
  16.  
  17. std::cout << "The valid integer entered was: " << Size << std::endl;
  18. }
Success #stdin #stdout 0s 3344KB
stdin
a1
2b
c3d
4 e
f 5
6 7
8
stdout
Please enter an integer: Invalid input. Please try again(integer only): Invalid input. Please try again(integer only): Invalid input. Please try again(integer only): Invalid input. Please try again(integer only): Invalid input. Please try again(integer only): Invalid input. Please try again(integer only): The valid integer entered was: 8