在 C 中使用枚举类型的变量作为字符串的简单方法? [英] Easy way to use variables of enum types as string in C?

查看:16
本文介绍了在 C 中使用枚举类型的变量作为字符串的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的:

typedef enum { ONE, TWO, THREE } Numbers;

我正在尝试编写一个函数来执行类似于以下的 switch case:

I am trying to write a function that would do a switch case similar to the following:

char num_str[10];
int process_numbers_str(Numbers num) {
  switch(num) {
    case ONE:
    case TWO:
    case THREE:
    {
      strcpy(num_str, num); //some way to get the symbolic constant name in here?
    } break;
    default:
      return 0; //no match
  return 1;
}

不是在每种情况下都定义,有没有办法像我上面尝试的那样使用 enum 变量来设置它?

Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above?

推荐答案

没有内置的解决方案.最简单的方法是使用 char* 数组,其中枚举的 int 值索引到包含该枚举的描述性名称的字符串.如果您有一个稀疏的 enum(一个不从 0 开始或在编号中有间隙的),其中一些 int 映射足够高,可以创建一个数组-基于映射不切实际,那么您可以改用哈希表.

There's no built-in solution. The easiest way is with an array of char* where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse enum (one that doesn't start at 0 or has gaps in the numbering) where some of the int mappings are high enough to make an array-based mapping impractical then you could use a hash table instead.

这篇关于在 C 中使用枚举类型的变量作为字符串的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆