c++char

Comparing with more than one char in C++


Say I have an input that is stored in a char c, and in a conditional I need to check whether it is either of two different characters, for example 'n' and 'N'. It's obvious that I can make a conditional with a logical OR operator:

if(c == 'n' || c == 'N')
...

However, if there are significantly more than just two conditions, than that will require significantly more logical operators to be used, and it will become tedious to write, look at, and edit. Is there a way to condense this process? To make it look like something along the lines of this:

if(c == '[N][n]')
...

Does anything of the sort exist?


Solution

  • You can make a string of your matching characters and see if the character in question exists in the string:

    char c;
    std::string good_chars = "nNyYq";
    if(good_chars.find(c) != std::string::npos) {
        std::cout << "it's good!";
    }