1 /*-----------------------------
2 enum.c -- 使用枚举类型的值
3 -----------------------------*/
4
5 #include <stdio.h>
6 #include <string.h>
7 //#include <stdbool.h> //C99特性
8
9 #define LEN 30
10
11 char* s_gets(char *st, int n);
12
13 enum spectrum {red, orange, yellow, green, blue, violet};
14 const char *colors[] = {"red", "orange", "yellow", "green", "blue", "violet"};
15
16 int main()
17 {
18 char choice[LEN];
19 int color;
20 bool color_is_found = false;
21
22 puts("Enter a color (empty line to quit):");
23
24 while (s_gets(choice, LEN) != NULL && choice[0] != '\0')
25 {
26 for (color = red; color != violet; ++color)
27 {
28 if (strcmp(choice, colors[color]) == 0)
29 {
30 color_is_found = true;
31 break;
32 }
33 }
34
35 if (color_is_found)
36 switch (color)
37 {
38 case red:
39 puts("Roses are red.");
40 break;
41 case orange:
42 puts("Poppies are orange.");
43 break;
44 case yellow:
45 puts("Sunflowers are yellow.");
46 break;
47 case green:
48 puts("Grass is green");
49 break;
50 case blue:
51 puts("Bluebells are blue");
52 break;
53 case violet:
54 puts("Violets are violet");
55 break;
56 }
57 else
58 printf("I don't know about the color %s.\n", choice);
59
60 color_is_found = false;
61
62 puts("Next color, please (empty line to quit):");
63 }
64
65 puts("Goodbye");
66
67 return 0;
68 }
69
70 char* s_gets(char *st, int n)
71 {
72 char *ret_val, *find;
73
74 if (ret_val = fgets(st, n, stdin))
75 {
76 if (find = strchr(st, '\n'))
77 *find = '\0';
78 else
79 while (fgetc(stdin) != '\n') continue;
80 }
81
82 return ret_val;
83 }