Chinaunix首页 | 论坛 | 博客
  • 博客访问: 362960
  • 博文数量: 94
  • 博客积分: 2500
  • 博客等级: 少校
  • 技术积分: 823
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-04 16:49
文章分类

全部博文(94)

文章存档

2015年(1)

2011年(1)

2010年(3)

2008年(8)

2007年(55)

2006年(26)

我的朋友

分类: C/C++

2006-07-28 09:46:37

学C语言的人都知道,每个枚举常量对应一个整形数字,很多时候可以像整形一样使用;
但枚举类型也有不它不方便的地方,比如,就不能直接输出枚举类型的字符串常量。举例说明,定义了枚举类型
typedef enum {North,East,South,West} directionT;
在程序中定义了变量
directionT dir=North;
如果想用
printf("The direction is %s",dir);
之类的语句直接输出
The direction is North
是做不到的,无论采用%s或%d,或者在dir前加强制类型转换。
 
所以可能的解决办法是函数
char * StringDirectionT(directionT dir)
{
        switch(dir)
        {
                case North : return "North";
                case East  : return "East";
                case South : return "South";
                case West  : return "West";
                default    : printf("Illegal direction value!\n;
        }
}
然后用语句
printf("The direction is %s \n",StringDirectionT(dir));
来输出。
只是这样做实在有些麻烦,不过我到现在能想到的解决办法也就是这个了。
 
阅读(15425) | 评论(5) | 转发(0) |
给主人留下些什么吧!~~

诗词与花儿2018-02-05 15:01:27

haisen888:用红替换,这个很牛B

#define enumToStr(DIR)  "\""#DIR"\""
typedef enum {North,East,South,West} directionT;
在程序中定义了变量
printf("The direction is %s",enumToStr(North));

这种方法只是将其转变成字符串,如果输入数字,就不能输出对应的枚举。

回复 | 举报

Q__Q112015-05-08 23:08:18

c语言枚举
http://www.alex999.com/c_language_enumeration.html

Q__Q112015-05-08 23:08:06

c语言枚举
http://www.alex999.com/c_language_enumeration.html

haisen8882014-03-16 18:43:36

用红替换,这个很牛B

#define enumToStr(DIR)  "\""#DIR"\""
typedef enum {North,East,South,West} directionT;
在程序中定义了变量
printf("The direction is %s",enumToStr(North));