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...}
#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 ) {
returntrue;
}
}
// User's choice is invalid
returnfalse;
}
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'))"