Input validation - range of ints and data type check

Hello,

I am having issues with my input validation part of my code. I am asking the user for an int, and I need to make sure 1) it is truly an int, and 2) it is either 1, 2, or 3. I know how to do those things separately, but when I try to put them together, it doesn't work properly.

I have tried numerous different loops and syntax, but this is what I currently have:

1
2
3
4
5
6
7
8
9
10
11

// Input validation
	while (((choice != 1) && (choice != 2) && (choice != 3)) || !(cin >> choice))
	{
		cin.clear();
		cin.ignore();
		cout << "Please enter either 1, 2, or 3." << endl;
		cin >> choice;
		if ((choice == 1) || (choice == 2) || (choice == 3))
			break;
	}


The main problem in testing is going back and forth between data types. For instance, I would like for the user to be able to erroneously enter chars and ints not in the desired range, multiple times, in any order. That is where I am having issues.

Thank you for your help!
I would say use a switch statement. It will make things a lot easier.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
switch(choice)
{
case 1:
//code
//break or return
case 2:
//code
//break or return
case 3:
//code
//break or return
default:
std::cout << "Please enter either 1, 2, or 3." << std::endl;
std::cin >> choice;
}
You probably want to have your cin statement first. Something like:

1
2
3
4
5
6
    while(!(cin >> value)  || (value < 1 || value > 3))
    {
        cin.clear();
        cin.ignore(1000, '\n');
        cout << "error\n";
    }


Don't forget about short circuit evaluation problems.

https://en.wikipedia.org/wiki/Short-circuit_evaluation
Topic archived. No new replies allowed.