This is very helpful, but I was curious is there a way to use this piece of code in such a way
e.g. i only want the program to accept 100, 101, and 102 anything else i will give an error.
??
I would rather suggest, using a function, that return a bool. Put all the valid values in an array and search if the input matches any of the value in the valid numbers which are now elements in the array. The function return false or true, then you can use a while loop to test like you are doing in your first post.
Something like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
bool checkNum ( constint search ) {
bool value = false; // a bool to check
int array[] = {100, 104, 200, 201, 204};
int size = sizeof array / sizeof(int);
for ( int i = 0; i < size; i++ )
if ( array[i] == search ) {
value = true;
break; // once you have a match leave the for loop
}
if (!value) // if search is not true
cout <<
"Err: Invalid Input! "
<< endl;
return value;
}
then like your first statement:
1 2 3 4 5 6 7 8 9 10
// get a number from the user
int number;
string msg = "Enter one of these numbers 100, 104, 200, 201, 204: ";
cout << msg;
cin >> number;
while ( !checkNum(number) ) {
cout << msg;
cin >> number;
}
Of course, there are better way to do the searching. But for a few array numbers a for loop should do.