0

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

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"

我想要做的是让我的 sched_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);

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

4

2 回答 2

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

希望有帮助。

于 2012-05-02T15:38:35.400 回答
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 方法,您可以为您的日子添加额外的任意分类,而无需一直进行范围比较

于 2012-05-02T18:05:42.983 回答