/* InputExample.cpp Dave Klick CIS 150 2017-02-28 Demonstrates how to handle unexpected input gracefully. */ #include #include using namespace std; int getInt(string prompt, int min, int max); int main() { int n = getInt("Enter year of birth ", 1800, 2050); return 0; } int getInt(string prompt, int min, int max) { int val; bool valid = false; while (!valid) { // Keep looping while we do not have valid input cout << prompt << "(" << min << "-" << max << "): "; cin >> val; if (!cin) { // This is true if the wrong data type was entered cout << "Invalid integer\n"; cin.clear(); // Clears the input error condition cin.ignore(10000, '\n'); // Clears the input buffer } else { // The rest of this is normal data validation if (val < min) cout << "Error: Below minimum of " << min << '\n'; else if (val > max) cout << "Error: Above maximum of " << max << '\n'; else valid = true; // Input was valid, so set flag to stop loop } } return val; }