I'm making a program that finds the square root of a number. With intergers, it works fine, but I want the program to show and error if the user tries to enter a character or negative number.
I can make an error show with negative numbers, but anytime I use a char, the program loops infinitely. Does anyone know a workaround?
int CheckInput( int min )
{
int menuChoice; // Used to determine correct action.
bool invalid; // Used to check if input is valid.
do
{
invalid = false;
if ( !( cin >> menuChoice ) )
{
cout << "Invalid character, please try again.\n";
cin.clear(); // This statement will clear the infinite loop.
invalid = true;
}
elseif ( menuChoice < min )
{
cout << "Please enter a number larger than " << min << ".\n";
invalid = true;
}
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
// Clears the buffer for future input.
}
while( invalid );
return menuChoice;
}