Loop through an array

I'm trying to write a function that will read in an operator by utilizing a c string array. The array are "/+-*cCxX". If a a match, return true, if not return false.
Thanks.
1
2
3
4
5
6
7
8
9
10
11
  bool readOperator (const char validO[], char & op)
{
	cin >> op;
	for (int i = 0; i < 9; i++)
	{
		if (validO[i]==0)
			return true;
		else
			return false;
	}
}
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
#include <iostream>
#include <cstring>

bool is_valid( const char valid_operators[], char candidate_op )
{
    // if candidate_op is not the null character
    // and candidate_op is one of the characters in valid_operators, return true
    // http://en.cppreference.com/w/cpp/string/byte/strchr
    return candidate_op != 0 && std::strchr( valid_operators, candidate_op ) != nullptr ;
}

char get_operator()
{
    static constexpr char valid_operators[] = "/+-*cCxX" ;

    char ch ;
    std::cout << "operator (one of '" << valid_operators << "' )? " ;
    std::cin >> ch ;

    if( is_valid( valid_operators, ch ) ) return ch ;

    std::cout << "invalid input '" << ch << "' try again.\n" ;
    return get_operator() ; // try again
}

int main()
{
    char c = get_operator() ;
    std::cout << "operator: '" << c << "'\n" ;
}
Topic archived. No new replies allowed.