如何在没有映射的情况下在枚举和字符串之间进行转换?

How can I convert between enum and cstring without map?

本文关键字:之间 字符串 转换 情况下 映射 枚举      更新时间:2023-10-16

我以前见过这个问题,但使用地图或向量,但我不能在我的项目中使用外部库,所以我需要找出另一种方法。为了转换为 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;

它有单引号,所以它返回字符,作为整数等于 0。转换为指针时,这是一个空指针。当您尝试取消引用myStrComp()中的空指针时,会发生访问冲突。

相反,您可以使用return "";返回空字符串。

简化typeName的可能方法是使用数组:

const char* typeName[] = {"", "first", "second", "third", "fourth"};
if (myStrComp(name, typeName[i]) == 0) 

(如果i超出范围,这将导致访问冲突。

若要回答您的问题,可以使用查找表将enums 与文本相关联:

struct Entry
{
type  enum_type;
const char * enum_text;
};
Entry enum_conversion_table[] =
{
{none, "none"},
{first, "first"},
{second, "second"},
{third,  "third"},
{fourth, "fourth"},
};
static const size_t conversion_table_capacity =
sizeof(conversion_table) / sizeof(conversion_table[0]);

enum转换为文本:

  1. 在表中搜索具有键枚举的条目。
  2. 返回指向条目的文本字段的指针(如果找到(或 nullptr(如果未找到(。

从文本转换为enum

  1. 在表中搜索包含键枚举文本的条目。
  2. 如果找到,则返回枚举值
  3. ,或者为"unknown"创建另一个枚举值并返回该值。

此技术:
1.不使用任何库。
2.数据可以放入常量数据部分并存储到只读存储器中。
3.代码可以直接访问数据。
4. 数据在main()之前初始化。