Long Boolean statement shorthand?

I was wondering if there was a way to shorten long boolean statements like the following.

if ((choice != 'w') && (choice != 's') && (choice != 'a') && (choice != 'd') && (choice != 'q'))
{...inform user that input was invalid...}

In my program the statement works just fine, but at times I find that these statements can become very long, as well as cumbersome. I suppose what I'm asking is if there's a "shorthand' way to do this. Like:

if (choice != 'w','s','a','d','q')
{...inform user that input was invalid...}

Any insight would be helpful. Cheers!!
If you have a lot of valid characters, you could utilize a container to store them for comparison with user's input.

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
29
30
31
#include <vector>
#include <iostream>

bool isChoiceValid( const std::vector<char> &validCharacters , char userChoice )
{
    // Return true if user's choice matches any characters in this container
    for( auto x : validCharacters ) {
        if( userChoice == x ) {
            return true;
        }
    }

    // User's choice is invalid
    return false;
}

int main ()
{
    // Make a list of all valid characters or choices
    std::vector<char> validCharacters = { 'w' , 's' , 'a' , 'd' , 'q' };

    // Prompt for choice
    char choice;
    std::cout << "Enter your choice: ";
    std::cin >> choice;

    
    if( !isChoiceValid( validCharacters , choice) ) {
        std::cout << "Your choice is invalid";
    }
}



If you really want to stick with boolean expressions, you can also consider this option. You will still use a long series of if else statements, but at least, it won't be a long single line like "if ((choice != 'w') && (choice != 's') && (choice != 'a') && (choice != 'd') && (choice != 'q'))"
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
29
30
31
32
33
34
35
36
#include <iostream>



int main ()
{
    // Prompt for choice
    char choice;
    std::cout << "Enter your choice: ";
    std::cin >> choice;

    bool choiceIsValid = false;

    if( choice == 'w' ) {
        choiceIsValid = true;
    }
    else if( choice == 's' ) {
        choiceIsValid = true;
    }
    else if( choice == 'a' ) {
        choiceIsValid = true;
    }
    else if( choice == 'd' ) {
        choiceIsValid = true;
    }
    else if( choice == 'q' ) {
        choiceIsValid = true;
    }
    else {
        choiceIsValid = false;
    }

    if( !choiceIsValid ) {
        std::cout << "Your choice is invalid";
    }
}
Last edited on
Perfect! That first option never crossed my mind. Learned something new today; thanks!!
Alternatively:

1
2
3
4
    const std::string valid_choices = "wsadq";
     if ( valid_choices.find(choice) == std::string::npos ) {
          // inform user that input was invalid
    }
Topic archived. No new replies allowed.