• Source
    1. #include <iostream>
    2. #include <limits>
    3.  
    4. using namespace std;
    5.  
    6. int main()
    7. {
    8. double input = -1;
    9. bool valid= false;
    10. do
    11. {
    12. cout << "Enter a number: " << flush;
    13. cin >> input;
    14. if (cin.good())
    15. {
    16. //everything went well, we'll get out of the loop en return the value
    17. valid = true;
    18. }
    19. else
    20. {
    21. //something went wrong, we reset the buffer's state to good
    22. cin.clear();
    23. //and empty it
    24. cin.ignore(numeric_limits<streamsize>::max(),'\n');
    25. cout << "Invalid input; please re-enter." << endl;
    26. }
    27. } while (!valid);
    28. }