Say I already have a code for restricting alphabet input from another topic , I want to restrict the input to only allowing certain numbers such as
1 9 14 32 63, these numbers have no pattern is there an easy way to make this happen
Thanks DJ
1 2 3 4 5 6 7
if (cin.fail()){
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n'); //c++ site
continue;//repeats quickly
}
If you only have that many numbers to restrict, then just use a switch() statement.
If you are not familiar, a switch statement is just a group of if statements that compare only integers.
So, Ex:
1 2 3 4 5 6 7 8 9 10
cin>>a;
switch(a){
case 1:
cout<<"Oops! Try again!\n";
break;
case 9:
cout<<"Oops! Try again!\n";
break;
}
The catch is, by comparing, I mean if a == 1, or a == 9.
So really,
case 1:
really just means
if(a == 1)
If you have a bunch of numbers, then this may not be ideal for you. But for only 5 values, the best way is just a switch statement
Thanks a lot, just one more question I actually have quite a few numbers to insert
about 25, is this a problem for the switch function? i see it as working but practicality?
Perhaps a vector initialized with all the valid numbers, get input, cycle through looking for a match, if no match then get input again. Saves from a long switch statement.
Sorry I was unable to get back to this earlier, I haven't encountered the use of vectors . My program specification doesn't exactly say use them but. What about using an array?