How to use cin.clear ??

Hi, I'm working on my school project and having an issue with using cin.clear.
I want the users to input only the number (choices of 1,2,3 or 4).
Below is the code that I am working on.
If I run the program and enter invalid choice such as characters, then the program asks the user to input valid data.
But my problem is if I enter something such as 3a, then the program runs option 3...

How do I fix this problem? Please help!

int main()
{
//declare variables
int scores[SIZE];
//read data from file and retrieve size
int size = readData(scores);
if (size>0)
{
bool flag = true;

//loop until user quits
do
{

//display menu options
int choice;
cout << "\n Welcome! ";
cout << "\nSearch score..............Enter 1";
cout << "\nGenerate stats file.......Enter 2";
cout << "\nPrint scores..............Enter 3";
cout << "\nQuit......................Enter 4";
cout << "\nPlease select 1, 2, 3, or 4: ";
cin >> choice;

//switch case to handle user request
switch (choice)
{
case 1:int search;
cout << "\nEnter score to search for: ";
cin >> search;
searchScore(scores, size, search);
break;
case 2:findMaxMinScores(scores, size);
break;
case 3:displayScores(scores, size);
break;
case 4:flag = false;
break;
default:cout << "\nInvalid choice. Please enter valid number.";
break;
}

if (cin.fail())
cout << "\nInvalid choice. Please enter valid number." << endl;
cin.clear();
cin.ignore();


} while (flag);
}
else
cout << "\nData file not found.";

return 0;
}
Put your code in code brackets so its easier to read.
Topic archived. No new replies allowed.