fork download
  1. #include <iostream>
  2. #include <limits>
  3.  
  4. int main()
  5. {
  6. int input;
  7. char c; //used for checking left over characters in buffer
  8. std::cout << "Please enter an integer: ";
  9. while( !(std::cin >> input) || //check if there are bad flags set
  10. ( std::cin.get( c ) && c != '\n' ) ) //check if anything left in buffer
  11. {
  12. std::cin.clear(); //clear error flags
  13. std::cin.ignore( std::numeric_limits<std::streamsize>::max() , '\n' ); //ignore anything left in buffer
  14. std::cerr << "Invalid input. << std::endl << Please try another integer: ";
  15. }
  16. std::cout << "You entered: " << input << std::endl;
  17. return 0;
  18. }
Success #stdin #stdout #stderr 0s 3300KB
stdin
a1
2a
3 a
a 4
5
stdout
Please enter an integer: You entered: 5
stderr
Invalid input. << std::endl << Please try another integer: Invalid input. << std::endl << Please try another integer: Invalid input. << std::endl << Please try another integer: Invalid input. << std::endl << Please try another integer: