How to check input against entire array?

If I have a char array that that looks like

char array[] = {'a', 'b', 'c'};

How can I check user input against all of these values at once?
1
2
3
4
if ( user_value == array[0] || user_value == array[1] || user_value == array[2])
{
   Do action;
}
Last edited on
Is there a way to do it if there were many more elements?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>

int main()
{
    const char array[] = { 'a', 'b', 'c', '.', 'd', 'e', 'f', 'g', '?' } ;
    const std::string str = "abc.defg?" ;

    char input ;
    std::cin >> input ;

    if( std::find( std::begin(array), std::end(array), input ) != std::end(array) )
       std::cout << "input is one of the characters in array\n" ;

    if( str.find(input) != std::string::npos )
       std::cout << "input is one of the characters in str\n" ;
}
One more:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <iterator>
#include <set>

int main()
{
    const char array[] = { 'a', 'b', 'c', '.', 'd', 'e', 'f', 'g', '?' } ;
    const std::set<char> values( std::begin(array), std::end(array) );

    char input ;
    std::cin >> input ;

    if( 1 == values.count( input ) )
       std::cout << "input is one of the characters in values\n" ;

  return 0;
}
It tells me begin is not a member of the standard library, what's likely the cause of this? Using dev-c++

Edit: Ran it in visual studio c++ and it worked, I don't know why that is.
Last edited on
You did not include iterator library or you are not using a c++11 compatible compiler. If you compile on the command line, try to provide the option
-std=c++11
This equivalent code would work with a somewhat old compiler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <algorithm>

int main()
{
    const char array[] = { 'a', 'b', 'c', '.', 'd', 'e', 'f', 'g', '?' } ;
    const char* const end = array + sizeof(array) ; // sizeof(char) == 1

    char input ;
    std::cin >> input ;

    if( std::find( array, end, input ) != end )
       std::cout << "input is one of the characters in array\n" ;
}
Last edited on
Topic archived. No new replies allowed.