I was tinkering with a recent program I made for my programming class which determines the difference between the ages of two people and I discovered a little bug: If the person enters something other than a numerical value, cin kinda wacks out. Here is the code I'm using to fix the problem:
It works, but if the user enters more than 4 characters, the program either ignores it or gives me an exception of some sort. Is there a better way to flush the buffer (I'm sort of a newb so I'm not to familiar with the methods for doing this yet)?Code:int ErrorHandler() { if(std::cin.fail()) { std::cerr << "Input error \n"; std::cin.clear(); //Reset input failure indicators //Flushing buffer char BadInput[5]; std::cin >> BadInput; return 0; } else { return 1; } }




Reply With Quote