-
cin.fail() function
Ill throw my code at you first
Code:
int menu(int &answer)
{
do {
cout << "----Menu----" << endl
<< "1 something" << endl
<< "2 something" << endl
<< "3 something" << endl
<< "Please select an option (1, 2, or 3): ";
cin >> answer;
if (( cin.fail() ) == 1) {
cin.clear();
cout << "Please enter a valid option" << endl;
}
else if ((answer != 1) && (answer != 2) && (answer != 3)) {
cout << "Please enter a valid option" << endl;
}
} while ( (answer != 1) && (answer != 2) && (answer != 3) );
return answer;
}
now it seems to handle most error type inputs except if u enter a character and i thought cin.fail and what i have done might be able to deal with it but it doen't, Have i used the function wrong? And if so could i have some help in correcting it. thanks.
-
It's messy, but you could try something like this:
Code:
bool Int = false;
bool validInt = false;
while(!Int && !validInt)
{
cin >> answer;
if(cin.fail())
{
cin.clear();
cin.ignore(10000, '\n');
cout << "you didn't enter an integer" << endl;
cout << "Please enter a valid option" << endl;
}
else if((answer < 1) || (answer > 3))
{
cout << "the int must be 1, 2, or 3" << endl;
cout << "Please enter a valid option" << endl;
}
else
{
Int = true;
validInt = true;
}
}