cin error... Need help!

I'm trying to ask the user to enter one integer value: 1,2,3 or 4.
But if the user enters 2a or 2p for example, then the program proceeds with choice 2. How do I fix this error?

Below is the part of my codes.

int main()
{
//Declare variables
int scores[SIZE];
//Read data from file and retrieve scores
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(numeric_limits<streamsize>::max(), '\n');

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

return 0;
}
Please put your code in code tags, reading code without them is very frustrating.

This code is a simple recreation of your issue. Always make the code you post as small as it can be while still being informative to the problem.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main() {
	int code;
	std::cout << "Code: ";
	std::cin >> code;
	std::cout << code << std::endl;
	return 0;
}


If you run that, and then enter something like '2a', you'll get 2 as your output.

In your case, your best bet might be getting your input in a string format first. Validate the input there, i.e. assert there's no non-numerical characters. After validation, you can convert your string to an integer. This can be done with std::stringstream or something like std::stoi.
Thanks! I tried using string format and it works :)
Sorry for not putting my code in code tags.. Will make sure to do that next time!
Topic archived. No new replies allowed.