c++ input until successful
xxxxxxxxxx
/*
* clear the buffer
*/
void clearBuffer()
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
/*
* get input from the user
* @type T - the type of input to get
* @param toPrint - the string to print to the user in order to get the input
* @param isValid - a lambda function that check if the input that the user put is valid
* @return the input of the user
*/
template <class T>
T getUserInput(const std::string& toPrint, std::function<bool(const T&)> isValid)
{
T userInput;
bool isFail = false;
do
{
std::cout << toPrint;
std::cin >> userInput;
isFail = std::cin.fail();
if (isFail)
{
clearBuffer(); // clear the buffer
system("cls"); // clear the console
}
} while (isFail || !isValid(userInput)); // run until the input is valid
return userInput;
}