如何在没有映射的情况下在枚举和字符串之间进行转换?
How can I convert between enum and cstring without map?
我以前见过这个问题,但使用地图或向量,但我不能在我的项目中使用外部库,所以我需要找出另一种方法。为了转换为 cstring,我正在使用一个带有开关大小写的函数并且它可以工作,但从 cstring 转换为枚举并没有按计划进行。
我想出的将 cstring 转换为枚举的方法是首先将枚举转换为 int(none、first、second 等变为 0、1、2 等(,以便我可以使用 for 循环遍历不同的枚举。接下来,使用枚举到 cstring 函数,我将传入的字符串与转换函数给出的字符串进行比较。如果它们相等,则设置枚举。这似乎是一种非常复杂的方法,不出所料,我无法让它工作。
这是我所有的测试代码,setType 函数是出错的地方。
enum type { none, first, second, third, fourth };
const char* typeName(type name);
type setType(char* name); // trouble here
int myStrComp(const char *str1, const char *str2); // compare cstrings
int main() { // test the function
char testName[] = "second";
type testType = setType(testName);
std::cout << typeName(testType) << std::endl; // should print "second"
}
const char* typeName(type name) { // convert enum to cstring
switch (name) {
case none: return ' '; break;
case first: return "first"; break;
case second: return "second"; break;
case third: return "third"; break;
case fourth: return "fourth"; break;
}
}
type setType(char* name) {
type temp;
for (int i = 0; i < 4; i++) { // I know, inefficient
temp = static_cast<type>(i); // but there's only 5 to check
if (myStrComp(name, typeName(temp)) == 0) {
return temp;
}
}
return none; // shouldn't get here
}
int myStrComp(const char *str1, const char *str2) {
while (*str1 == *str2) {
if (!*str1) {
return 0; // strings are equal
}
str1++;
str2++;
}
return *str1 - *str2; // how different are they alphabetically
}
case none: return ' '; break;
它有单引号,所以它返回字符