打印文本而不是 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)\n");
scanf("%d",&j);
TheDay = Days(j);
//how to PRINT THE VALUES stored in TheDay
printf("%s",TheDay); // isnt working
return 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
C 中的枚举是在代码中具有方便名称的数字。它们不是字符串,并且源代码中分配给它们的名称不会编译到您的程序中,因此在运行时无法访问它们。
获得所需内容的唯一方法是自己编写一个函数,将枚举值转换为字符串。例如(假设您将
enum Days
的声明移到main
之外):或者,您可以使用数组作为映射,例如
但是在这里您可能想要为了安全起见,在枚举中分配
Sunday = 0
...我不确定 C 标准是否要求编译器从 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 ofmain
):Alternatively, you could use an array as a map, e.g.
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).我使用这样的内容:
在文件“EnumToString.h”中:
然后在任何头文件中进行枚举声明,day enum.h
然后在名为 EnumToString.c 的文件中:
然后在 main.c 中:
这将生成“自动“以这种方式声明并包含在“EnumToString.c”中的任何枚举的字符串
I use something like this:
in a file "EnumToString.h":
then in any header file you make the enum declaration, day enum.h
then in a file called EnumToString.c:
then in main.c:
this will generate "automatically" the strings for any enums declared this way and included in "EnumToString.c"
我通常这样做的方法是将字符串表示形式以相同的顺序存储在单独的数组中,然后使用枚举值索引该数组:
The way I usually do this is by storing the string representations in a separate array in the same order, then indexing the array with the enum value:
我知道我参加聚会迟到了,但是这个怎么样?
这样,您就不必手动保持
enum
和char*
数组同步。如果您像我一样,很可能您稍后会更改enum
,并且char*
数组将打印无效字符串。这可能不是普遍支持的功能。但据我所知,大多数现代 C 编译器都支持这种指定的初始样式。
您可以在此处了解有关指定初始值设定项的更多信息。
I know I am late to the party, but how about this?
This way, you do not have to manually keep the
enum
and thechar*
array in sync. If you are like me, chances are that you will later change theenum
, and thechar*
array will print invalid strings.This may not be a feature universally supported. But afaik, most of the mordern day C compilers support this designated initialier style.
You can read more about designated initializers here.
C 中的
enum
并没有真正按照您期望的方式工作。您可以将它们想象为美化的常量(还有一些与成为此类常量的集合相关的额外好处),并且您为“Sunday”编写的文本实际上被解析为在编译过程中,文本最终会被丢弃。简而言之:要做你真正想做的事情,你需要保留一个字符串数组或创建一个函数来从枚举值映射到你想要打印的文本。
enum
s in C don't really work the way you're expecting them to. You can think of them kind of like glorified constants (with a few additional benefits relating to being a collection of such constants), and the text you've written in for "Sunday" really gets resolved to a number during compilation, the text is ultimately discarded.In short: to do what you really want you'll need to keep an array of the strings or create a function to map from the enum's value to the text you'd like to print.
C 中的枚举基本上是自动排序整数值命名列表的语法糖。也就是说,当您有以下代码时:
您的编译器实际上会输出以下内容:
因此,将 C 枚举作为字符串输出对于编译器来说不是有意义的操作。如果您希望获得人类可读的字符串,则需要定义从枚举转换为字符串的函数。
Enumerations in C are basically syntactical sugar for named lists of automatically-sequenced integer values. That is, when you have this code:
Your compiler actually spits out this:
Therefore, outputting a C enumeration as a string is not an operation that makes sense to the compiler. If you want to have human-readable strings for these, you will need to define functions to convert from enumerations to strings.
这是使用宏的更简洁的方法:
我不确定这是否是完全可移植的黑白预处理器,但它可以与 gcc 一起使用。
顺便说一句,这是 c99,因此如果将其插入 (在线编译器)ideone,请使用
c99 strict
一个>。Here's a cleaner way to do it with macros:
I'm not sure that this is totally portable b/w preprocessors, but it works with gcc.
This is c99 btw, so use
c99 strict
if you plug it into (the online compiler) ideone.我喜欢在 dayNames 中包含枚举。
为了减少打字,我们可以执行以下操作:
I like this to have enum in the dayNames.
To reduce typing, we can do the following:
问题是你只想把名字写一次。
我有一个像这样的 ider:
它使用一个结构来插入枚举,以便字符串打印机可以遵循每个枚举值定义。
>error is get_other_string, number is -203
与 enum 的区别是,如果数字重复,构建器无法报告错误。
如果你不喜欢写数字,
__LINE__
可以替换它:>day Wednesday, number is 3
>day Monday, number is 1
>The question is you want write the name just one times.
I have an ider like this:
it uses a struct to insert enum, so that a printer to string could follows each enum value define.
>error is get_other_string, number is -203
The difference to enum is builder can not report error if the numbers are repeated.
if you don't like write number,
__LINE__
could replace it:>day Wednesday, number is 3
>day Monday, number is 1
还有另一种解决方案:创建您自己的动态枚举类。意味着您有一个 struct 和一些函数来创建新的枚举,该枚举将元素存储在 struct 中,并且每个元素都有一个名称字符串。您还需要某种类型来存储单个元素、比较它们的函数等等。
这是一个例子:
枚举的函数应该在它们自己的翻译单元中,但我在这里将它们组合起来以使其更简单。
优点是该解决方案非常灵活,遵循 DRY 原则,您可以将信息与每个元素一起存储,您可以在运行时创建新的枚举,并且可以在运行时添加新元素。
缺点是比较复杂,需要动态内存分配,不能在
switch
-case
中使用,需要更多内存并且速度较慢。问题是在需要的情况下是否不应该使用更高级别的语言。There is another solution: Create your own dynamic enumeration class. Means you have a
struct
and some function to create a new enumeration, which stores the elements in astruct
and each element has a string for the name. You also need some type to store a individual elements, functions to compare them and so on.Here is an example:
The functions of enumeration should be in their own translation unit, but i combined them here to make it simpler.
The advantage is that this solution is flexible, follows the DRY principle, you can store information along with each element, you can create new enumerations during runtime and you can add new elements during runtime.
The disadvantage is that this is complex, needs dynamic memory allocation, can't be used in
switch
-case
, needs more memory and is slower. The question is if you should not use a higher level language in cases where you need this.使用宏和字符串化运算符(#)我们可以实现这一点......
Using a Macro and stringize operator(#) we can achieve this....
来自使用 TRACE_EVENT() 宏(第 3 部分)
From Using the TRACE_EVENT() macro (Part 3)
我对此很陌生,但 switch 语句肯定会起作用
i'm new to this but a switch statement will defenitely work
TheDay 映射回某种整数类型。因此:
尝试将 TheDay 解析为字符串,并且会打印出垃圾或崩溃。
printf 不是类型安全的,并且信任您将正确的值传递给它。要打印出值的名称,您需要创建一些方法来将枚举值映射到字符串 - 查找表、巨型 switch 语句等。
TheDay maps back to some integer type. So:
Attempts to parse TheDay as a string, and will either print out garbage or crash.
printf is not typesafe and trusts you to pass the right value to it. To print out the name of the value, you'd need to create some method for mapping the enum value to a string - either a lookup table, giant switch statement, etc.