The Problem
When you fail to read something from std::cin, the input is not consumed, the buffer still contains data. Trying to read again will try to read the same invalid data (e.g. characters, when you're looking for digits) and that's why you end up with an infinite loop.
To fight this, you need to
- remove the error flag from the std::cin
- tell std::cin to ignore anything from the input that you do not want there (in your case everything until the end of the line)
The Fix
Please, see your fixed code below:
void errorHandling()
{
bool valid = false;
int operation = 0;
while (valid == false)
{
std::cout << std::endl << "\tEnter choice: ";
if (!std::cin >> operation) // Did reading from std::cin fail?
{
std::cin.clear(); // Clear the error flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Ignore anything until the new line character
}
if (operation >= 1 && operation <= 4)
valid = true;
else
std::cout << "\tInput range is from 1 to 4 only." << std::endl;
}
}