【问题标题】:How to print all the contents in enum in C?如何在C中打印枚举中的所有内容?
【发布时间】:2015-09-24 09:40:09
【问题描述】:

我正在尝试使用选项卡在一行中打印枚举中的所有内容以分隔每个衬衫尺寸。当我尝试编译我的程序时,它会打印出随机数而不是 S、M、L、XL。

这是我的程序:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

enum SIZE{S,M,L,XL};

  int i,j;

int main()
{
enum SIZE s;

int t[4][4]={1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7};

  int *p=t;

/********DISPLAY ARRAY******************/

printf("This is our inventory \n");

  for(s=S; s<=XL; s=(s+1))
  {
      printf("%d \t", t[s]);
  }

   printf("\n");

 for( i=0; i<4; i++)
 {
    for(j=0;j<4; j++)
      {
            printf("%d\t", *p++);
      }


    printf("\n");
 }
/*****************************************/

printf("\n\n");
system("PAUSE");
return 0;
}

output:

This is our inventory
2686668         2686684         2686700         2686716
1       2       3       4
5       6       7       8
9       1       2       3
4       5       6       7

按任意键继续。 . .


我不明白为什么要打印以下行:

2686668         2686684         2686700         2686716

相对于:

S             M               L              XL

谁能解释造成这种情况的原因?

【问题讨论】:

  • t 被声明为二维数组,但您将其打印为一维数组!
  • 在使用枚举之前可能想研究一下枚举是什么。

标签: c arrays for-loop enums


【解决方案1】:

C 中的枚举没有名称(参见 this tutorial

试试这个:How to convert enum names to string in c

【讨论】:

    【解决方案2】:

    作为@Longhup 答案的替代方案,您可以使用 X-Macros:

    #include <stdio.h>
    
    #define SIZES \
        X(S) \
        X(M) \
        X(L) \
        X(XL)  
    
    #define X(a) a,
    enum SIZE{SIZES};
    #undef X
    
    #define X(a) #a,
    static char *arr[] = {SIZES};
    #undef X
    
    int main(void)
    {
        int i;
    
        for (i = 0; i <= XL; i++) {
            printf("%s\n",arr[i]);
        }
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      线

      printf("%d \t", t[s]);
      

      正在打印 指针 值 (&amp;t[s][0]),而不是枚举类型的值,因此是奇怪的数字。

      不幸的是,枚举常量并没有什么魔力,可以让您根据相应的值显示标识符。我通常使用与枚举标识符对应的字符串数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多