枚举用法实例

来源:互联网 发布:程序员怎么自学 编辑:程序博客网 时间:2024/05/22 12:48

原先C语言中枚举用的不多,现在整理一篇,方便以后自己复习:

函数功能是在定义的颜色数组中查找是否有从键盘中输入的颜色,如果有则打印响应的字符串,否则打印未找到的信息,并提示是否重新输入。

/*使用枚举值*/#include <stdio.h>#include <string.h>#include <stdbool.h>enum spectrum {red, orange, yellow, green, blue, violet};//声明枚举const char *colors[] = {"red","orange","yellow", "green", "blue", "violet"};//字符串数组#define LEN 30int main(void){char choice [LEN];enum spectrum color;bool color_is_found = false;puts("Enter a color (empty line to quit):");while (gets(choice) != NULL && choice[0] != '\0')//while循环,与puts("Next color, please (empty line to quit):");配合实现循环输入的功能{for (color = red; color <= violet; color++)//在数组中寻找是否有想要查询的颜色{if (strcmp(choice , colors[color]) == 0){color_is_found = true;break;}}if (color_is_found)//当color_is_found标志为1时,打印响应的字符串switch (color)//choice 是字符串,switch接受的是数值的类型,所以此处使用的是color值。{case red: puts("Roses are red.");        break;case orange: puts("Poppies are orange.");break;case yellow: puts("Sunflowers are yellow.");break;case green: puts("Grass are green.");break;case blue: puts("Bluebells are blue.");break;case violet: puts("Violets are violet.")break;}elseprintf ("I don't know about the color %s.\n",choice);color_is_found = false;puts("Next color, please (empty line to quit):");}puts("Bye!");return 0;//返回值}
简单的总结:

枚举类型其实是用字符代表数字,方便记忆和使用,其实质还是数值。也就是说可以把它理解为助记符。

0 0
原创粉丝点击