So, I've been programming in C++ for a little while, and many of my programs involve checking for errors. For example, if a menu offers options 1, 2, 3, and 4, I have to handle situations like the user entering "three" or '#' instead. Presently, I use this:
int selection;
cout << "Enter your selection.\n";
cin >> selection;
while (cin.fail() || selection < 1 || selection > 4)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin >> selection;
cout << "Invalid input. Please ensure that your input is valid and try again: \n";
}
I am tired of having to type that over and over again in different programs, and often there is a lot of input validation like this required.
Does anyone know a faster/shorter way to do this in C++? It's quite possible that you more experienced coders will tell me that this is short as far as error checking goes, but if there is a shorter way, it's always good to know.
Please let me know if you need more clarification in the code or the question. Thank you in advance.