while loop validation

Is there a simpler way to write

1
2
3
4
5
6
7
8
9
10
	//Validating input to R,S,P and Q
while (my_choice != 'R' && my_choice != 'P' && my_choice != 'S' && my_choice != 'Q')//is there a simpler way to write this 
		{
				
				cout << "\nInvalid option. Please Try Again.\n"; 
				cout << "\nMake your choice [R,P,S]. Enter Q to Quit. ";
				cin  >> user_choice;//promotes user to enter a choice 
		
		}
return my_choice;
Last edited on
Since the letters are in sequence (P, Q, R, S) you can use something related to the ASCII code:

1
2
3
while (my_choice < 'P' || my_choice > 'S') {
    // invalid
}

Otherwise you can just put your validation code in a separate method:

1
2
3
bool validate_option (char my_option) {
    ...
}
Last edited on
isnt there any thing easier like
1
2
char my_choice;
while (!(my_choice=R ...) //i dont know how to go about it can some one help please  
Last edited on
Well it's just the same thing but applying De Morgan's rules:

 
while(!(my_choice == 'R' || my_choice == 'P' || ...))


but it doesn't seem to be easier...

Don't you like the little trick with the ASCII code? According to me, that's the easiest way.
Simpler ways?
It's just different logical equivalencies.
And minomic's original suggestion does seem to be fairly simple.
Not sure this is simpler...

And it's prob. overkill for just 4 options.

... but using string::find() does scale better.

Andy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
using namespace std;

char getChoice();

int main () {
    cout << "Your choice?\n";

    char choice = getChoice();

    cout << "Got choice \'" << choice << "\'\n";

    return 0;
}

// Validating input to R,S,P and Q
char getChoice() {
    char my_choice = '?'; // init to something else 
    const string options = "RSPQ";
    while (options.npos == options.find(my_choice))
    {
        cout << "\nInvalid option. Please Try Again.\n";
        cout << "\nMake your choice [R,P,S]. Enter Q to Quit. ";
        cin  >> my_choice; //promotes user to enter a choice (was user_choice)
    }
    return my_choice;
}


Note that in C code you can do a similar kind of thing using strstr() strchr()
Edit: yes, I "meant" strchr when I wrote strstr...
Last edited on
andywestken's solution is a very handy trick to remember. For efficiency, it's important to make the string const (or static).
Note that in C code you can do a similar kind of thing using strstr()

I think you meant strchr():
1
2
3
if (strchr("RSPQ", my_choice) == nullptr) {
    cout << "invalid input\n";
}
Topic archived. No new replies allowed.