I have built a string to enum converter, which converts a known set of strings that it receives into enum, in order to satisfy a function pointer. Some of you may recognize some elements of this question elsewhere. This is written in Arduino, so C++.
enum input {FIRMV, VALCN, RQSPC, LIDVM, LIDVC, PREVC, STPWM, CHPWM, STPER, CHPER, SHIGH, PREST, PREND, RQPRE, CLPRE,
RQDAT, CUPTC, LIDTC, CURPR, CUPTT, CUFAC, LIFAC, STFAC, MTFAC, PPFAC, PCOFF, CUPFM, CUPFC, LIDFM,
LIDFC, PREFC, FCPWM, FCPER, FHIGH, INVAL
};
input convert(String str) { //A string to enum converter. Strings are sequences of characters used in Arduinos.
if (str == "FIRMV") return FIRMV;
else if (str == "VALCN") return VALCN;
else if (str == "RQSPC") return RQSPC;
else if (str == "LIDVM") return LIDVM;
else if (str == "LIDVC") return LIDVC;
else if (str == "PREVC") return PREVC;
else if (str == "STPWM") return STPWM;
else if (str == "CHPWM") return CHPWM;
else if (str == "STPER") return STPER;
else if (str == "CHPER") return CHPER;
else if (str == "SHIGH") return SHIGH;
else if (str == "PREST") return PREST;
else if (str == "PREND") return PREND;
else if (str == "RQPRE") return RQPRE;
else if (str == "CLPRE") return CLPRE;
else if (str == "RQDAT") return RQDAT;
else if (str == "CUPTC") return CUPTC;
else if (str == "LIDTC") return LIDTC;
else if (str == "CURPR") return CURPR;
else if (str == "CUPTT") return CUPTT;
else if (str == "CUFAC") return CUFAC;
else if (str == "LIFAC") return LIFAC;
else if (str == "STFAC") return STFAC;
else if (str == "MTFAC") return MTFAC;
else if (str == "PPFAC") return PPFAC;
else if (str == "PCOFF") return PCOFF;
else if (str == "CUPFM") return CUPFM;
else if (str == "CUPFC") return CUPFC;
else if (str == "LIDFM") return LIDFM;
else if (str == "LIDFC") return LIDFC;
else if (str == "PREFC") return PREFC;
else if (str == "FCPWM") return FCPWM;
else if (str == "FCPER") return FCPER;
else if (str == "FHIGH") return FHIGH;
else return INVAL;
}
Is there a better way of converting the string to enum that doesn't involve slowly running through every layer of an if-else stack? Please let me know if more information is needed.
string
implementation"?String
in a switch statement? That was my initial thought. The compiler would basically create a table for you.else
is extraneous code in this case. The branching will work exactly the same without it. You could autogenerate this code from the a specification doc by cutting and pasting into Excel and writing a formula. Would take all of five minutes and would be highly reliable. There is no reason to get too clever about this.