Reputation: 111
I am making a simple program, where user needs to enter a few possible characters. I want possible inputs to be only i, c, l, v, h, k, f, s, x. I do realize I can do something like:
char a;
bool s(false);
cin>>a;
do
{
switch(a)
case 'i': ...
case 'c': ...
...
default: cout<<"Invalid input! Try again: "; cin>>a; s=true;
} while(s);
However, I am pretty sure there is a more gracious solution. I am guessing enumerations would be involved. Would anyone be so kind as to tell it to me, since I could not find absolutely anything on the subject.
Upvotes: 2
Views: 79
Reputation: 73426
An easy solution could be:
const string allowed{"iclvhkfsx"};
while ( cin.get(a) && allowed.find(a)== string::npos)
cout << "Incorect input, try again ! ";
The code loops until a valid char is entered (or eof is reached).
Such a solution could be generalized to other data types than chars by using basic_string<T>
(demo for integers). Of course, switch
is perfectly valid, but I think its benefit is higher whenever different input would most often require different processing.
Upvotes: 3