-2

I'm parsing a string coming from a 'black box' screen controller and thought I'd be able to use enum to interpret the various parameters. I'm trying to understand why my approach won't work and although I know its something to do with types and casts I can't seem to reach a conclusion. I'd like to know if its just fundamentally a wrong approach or I'm missing something more basic. The stream arrives as a string array terminated with \n and I split it but then need to analyse the first letter of each 'token' dealing with the value according to what 'letter' is in 'str[0]'.

obviously didn't get the point across, I'm not looking for a coded solution just an understanding of where my wrong assumptions are.


    enum TL_parEnum : char {X = 0, Y = 1, Z = 2};
    
    struct TL_params {
          bool seen;
          float value;
        };
        TL_params TL_parbuffer[9]{false,0};
    
    while (TL_parsub = strtok_r(TL_param, " ", &TL_param)) {
              char p = TL_parsub[0];
          switch (TL_parsub[0]) { 
          case 'Y' :
             TL_parbuffer[p].seen=true;
             TL_parbuffer[(TL_parEnum)p].value =atoi(&TL_parsub[1]);
    }

the above fails because (TL_parEnum)p doesn't evaluate through the enum I either get the char 'Y' or the ascii 59. BUT if I hardcode (TL_parnum)Y it works as expected.

I've tried casting to and from char, *char, even my own constructions like TL_parEnum(j) but I only get the ascii code or the letter not something that I can use to 'decode' the enum.

So am I making poor assumptions about how this should work?

Also this is for an embedded controller so I don't have access to all the C++ goodies and I'm wondering if that is a factor.

1 Answers1

1

enums are largely a compile-time feature; the fact that it's named Y isn't relevant once the code is compiled (aside from in debugging symbols). You can't convert from a character describing the name of an enum member to the member itself without manually coding a lookup table for it in some way. Even if j[0] contains 'Y', the program has no idea that that maps to the member Y with value 1 when it's time to execute the code.

If you want to enable this sort of conversion, I'd recommend writing a simple function with a switch statement for char that has cases for each ASCII character covered, and returns the appropriate enum member (with a default that raises an exception or terminates the program when an unrecognized character is provided).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Thank you ShadowRanger - and every one else who offered a comment. Knowing enums are compile time clarifies things. I was trying to avoid the very long switch table I'm about to write and just got lost in a maze of twisty passages. – Regmigrant Jul 30 '20 at 19:12