评估枚举

时间:2012-05-02 15:27:13

标签: c

有没有办法评估枚举?我有一个结合到结构中的枚举:

typedef enum {MW, TR} days;

typedef struct {
  int hour, min;
} Time;

typedef struct {
  char Dept[5];
  int course, sect;
  days meet_days;
  Time start, end;
  char instr[20];
} sched_record;

我对枚举的打印声明是:

 data[i].meet_days == MW ? "MW" : "TR"

我想要做的是让scode_record的typedef结构只打印带有MW的记录。该程序的“菜单”如下:

 fread(data, sizeof(sched_record), MAX_RECORD, filePointer);
        fclose(filePointer);
        printf("Enter the Department or A for any Department: ");
        scanf("%s", tempDept);
        printf("Enter the Course or 0 for any course: ");
        scanf("%d", &tempCourse);
        printf("Enter the Days; M = MW, T = TTH or D=Don't Care: ");
        scanf("%s", tempDay);
        printf("Enter the Time; A=Mornings, P=Afternoons or D=Don't Care: ");
        scanf("%s", tempTime);

我的sched_records按时间打印出来,简单说明:

 else if ((strcmp(tempDept, "A")==0) && tempCourse == 0 && (strcmp(tempDay, "D")==0) && (strcmp(tempTime, "P")==0)) {
                            if (data[i].start.hour >= 12) {  // <---Time comparison
                                printf("%s %d %d %2s %02d%02d %02d%02d %s\n", data[i].Dept, data[i].course, data[i].sect, data[i].meet_days == MW ? "MW" : "TR",
                                   data[i].start.hour, data[i].start.min, data[i].end.hour, data[i].end.min, data[i].instr);
                     }
                }

                else if ((strcmp(tempDept, "A")==0) && tempCourse == 0 && (strcmp(tempDay, "M")==0) && (strcmp(tempTime, "D")==0)) {
                        printf("\n%s %d", data[i].Dept, data[i].course);

我想知道是否有一种像时间比较这样简单的方法来对枚举做同样的事情。如果有的话,有人能告诉我吗?

2 个答案:

答案 0 :(得分:2)

您可以使用与任何其他整数变量相同的方式比较枚举值:

if (data[i].meet_days == MW)
  .....

或者,如果说你有一整天的枚举:

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

然后你可以测试这样的范围:

if (day >= Monday || day <= Friday)
  printf ("It's a weekday!\n");

希望有所帮助。

答案 1 :(得分:1)

另一种方法是定义你的枚举值以设置某个位...例如,确保天'星期一'到'星期五'都有一个特定的位集:

因此:

#define WEEKDAY 0x100
typedef enum {
 SUNDAY   = 1,
 MONDAY   = 2 | WEEKDAY,
 TUESDAY  = 3 | WEEKDAY,
 WEDNESDAY= 4 | WEEKDAY,
 THURSDAY = 5 | WEEKDAY,
 FRIDAY   = 6 | WEEKDAY,
 SATURDAY = 7
} days;

然后,在检查当天是否是工作日时:

if (day & WEEKDAY) {
 printf("Day %d is a weekday!\n", day);
}

你可以通过使用XMACRO来获得更好的...但我会把它作为OP的练习:)

使用bitflag方法可以为您的日子添加额外的任意分类,而无需始终进行远程比较