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

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

问题描述

  INT的main()
{  枚举天{周日,周一,周二,周三,周四,周五,周六};  天TheDay;  INT J = 0;  的printf(请输入星期(0〜6)\\ n天);  scanf函数(%d个,&安培; j)条;  TheDay =天数(J);  //如何打印保存在TheDay的VALUES  的printf(%S,TheDay); //心不是工作  返回0;
}


解决方案

用C枚举是有你的code里面方便的名字号码。他们不是字符串,在源$ C ​​$ C分配给他们的名字不会被编译到你的程序,所以它们不是在运行时使用。

要得到你想要的东西的唯一方法是编写翻译枚举值转换成字符串的函数自己。例如。 (这里假设你移动枚举日的声明之外

 为const char * getDayName(枚举日天)
{
   开关(天)
   {
      案例星期日:回归星期天;
      周一案例:回归星期一;
      / *等... * /
   }
}/ *然后,后来在主:* /
的printf(%S,getDayName(TheDay));

另外,你可以使用一个数组作为地图,例如。

 为const char * DayNames中[] = {星期日,星期一,星期二,/ * ...等等... * /};/ * ... * /的printf(%S,DayNames中[TheDay]);

但在这里,你可能会想要分配周日= 0 枚举是安全的......我不知道,如果C标准要求编译器开始枚举从0开始,尽管大部分人(我敢肯定,有人会评论来证实或否认这一点)。

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)\n");

  scanf("%d",&j);

  TheDay = Days(j);

  //how to PRINT THE VALUES stored in TheDay

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

  return 0;
}

解决方案

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.

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]);

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天全站免登陆