C ++ enumeration from char

Ok, I'm new to C ++. I got a Bjarne book and I am trying to execute a calculator code.

However, the compiler spits out an error about this section:

token_value get_token()
{
    char ch;

    do {        // skip whitespace except '\n'
        if(!std::cin.get(ch)) return curr_tok = END;
    } while (ch!='\n' && isspace(ch));

    switch (ch) {
        case ';':
        case '\n':
            std::cin >> WS;      // skip whitespace
            return curr_tok=PRINT;
        case '*':
        case '/':
        case '+':
        case '-':
        case '(':
        case ')':
        case '=':
            return curr_tok=ch;
        case '0': case '1': case '2': case '3': case '4': case '5':
        case '6': case '7': case '8': case '9': case '.':
            std::cin.putback(ch);
            std::cin >> number_value;
            return curr_tok=NUMBER;
        default:            // NAME, NAME=, or error
            if (isalpha(ch)) {
                char* p = name_string;
                *p++ = ch;
                while (std::cin.get(ch) && isalnum(ch)) *p++ = ch;
                std::cin.putback(ch);
                *p = 0;
                return curr_tok=NAME;
            }
            error("bad token");
            return curr_tok=PRINT;
}

The error she spits out:

calc.cpp:42: error: invalid conversion fromchar’ to ‘token_value’

token_value is an enumeration that looks like this:

enum token_value {
    NAME,       NUMBER,     END,
    PLUS='+',   MINUS='-',  MUL='*',  DIV='/',
    PRINT=';',  ASSIGN='=', LP='(',   RP=')'
};
token_value curr_tok;

My question is: how do I convert ch (from cin) to the associated enum value?

+5
source share
5 answers

You cannot implicitly drop from charin enum- you need to do this explicitly:

return curr_tok = static_cast<token_value> (ch);

But be careful! If none of your values enummatches yours char, then it will be difficult to use the result :)

+7
source

, (.. static_cast) , , (, PLUS) / , (, '+').

( ) switch/case , , :

    case '*':
      return curr_tok=MUL;
    case '/':
      return curr_tok=DIV;
+4

:

curr_tok = static_cast<token_value>(ch);

, . , undefined. , . " , , , ".

+1

I think that I would not explicitly set the values ​​of the enumeration characters and instead write a case for each character that is contained in the switch statement. The execution of this method will probably be more difficult to debug if something goes wrong, and the execution cost recording the case for each character is so low that you should not even consider it (if you are not writing for some extremely low-level embedded system and probably still not worth it).

0
source
return curr_tok=(token_value)ch;
-1
source

All Articles