从 C 枚举打印文本而不是值 [英] Print text instead of value from C enum

查看:16
本文介绍了从 C 枚举打印文本而不是值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{

  enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};

  Days TheDay;

  int j = 0;

  printf("Please enter the day of the week (0 to 6)
");

  scanf("%d",&j);

  TheDay = Days(j);

  //how to PRINT THE VALUES stored in TheDay

  printf("%s",TheDay);  //   isnt working

  return 0;
}

推荐答案

C 中的枚举是在代码中具有方便名称的数字.它们不是字符串,源代码中分配给它们的名称不会编译到您的程序中,因此它们在运行时无法访问.

Enumerations in C are numbers that have convenient names inside your code. They are not strings, and the names assigned to them in the source code are not compiled into your program, and so they are not accessible at runtime.

得到你想要的唯一方法是自己编写一个函数,将枚举值转换为字符串.例如.(假设您将 enum Days 的声明移到 main 之外):

The only way to get what you want is to write a function yourself that translates the enumeration value into a string. E.g. (assuming here that you move the declaration of enum Days outside of main):

const char* getDayName(enum Days day) 
{
   switch (day) 
   {
      case Sunday: return "Sunday";
      case Monday: return "Monday";
      /* etc... */
   }
}

/* Then, later in main: */
printf("%s", getDayName(TheDay));

或者,您可以使用数组作为映射,例如

Alternatively, you could use an array as a map, e.g.

const char* dayNames[] = {"Sunday", "Monday", "Tuesday", /* ... etc ... */ };

/* ... */

printf("%s", dayNames[TheDay]);

但是在这里您可能希望在枚举中分配 Sunday = 0 以确保安全...我不确定 C 标准是否要求编译器从 0 开始枚举,尽管大多数都这样做(我相信有人会发表评论来确认或否认这一点).

But here you would probably want to assign Sunday = 0 in the enumeration to be safe... I'm not sure if the C standard requires compilers to begin enumerations from 0, although most do (I'm sure someone will comment to confirm or deny this).

这篇关于从 C 枚举打印文本而不是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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