原先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 30
int 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;
}
else
printf ("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;//返回值
}
简单的总结:
枚举类型其实是用字符代表数字,方便记忆和使用,其实质还是数值。也就是说可以把它理解为助记符。