C語言之列舉型別
阿新 • • 發佈:2018-11-21
在C語言中,列舉型別(enumerated type)宣告符號名稱來表示整形常量。使用enum關鍵字,可以建立一個新“型別”並指定它可具有的值,如:
//建立spectrum作標記名,那enum spectrum作為一個型別名使用
enum spectrum { red, orange, yellow, green, blue, violet};
//使color作為該型別的變數,red、yellow這些符號常量被稱為列舉符(enumerator)
enum spectrum color;
(1)enum常量
從技術上看,blue和red為int型常量,這裡在預設情況下,常量被賦予0,1,2等。其中,red = 0, orange = 1。
(2)賦值
(3)enum的用法例項
程式示例使用預設值的方案,把red的值設定為0,使之成為指向字串“red”的指標的索引。
//使用列舉型別的值
#include <stdio.h>
#include <string.h> //提供strcmp()、strchr()函式原型
#include <stdbool.h> //C99特性
char * s_gets(char * st, int n);
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 (s_gets(choice, LEN) != NULL && choice[0] != '\0')
{
for (color = red; color <= violet; color++)
{
if (strcmp(choice, colors[color]) == 0)
{
color_is_found = true;
break;
}
}
if (color_is_found)
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("Roses are green.");
break;
case blue: puts("Bluebells are red.");
break;
case violet: puts("Violets are red.");
break;
}
else
printf("I dont know about the color %s.\n", choice);
color_is_found = false;
puts("Next color, please (empty line to quit):");
}
puts("Goodbye!");
return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
char * find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n'); //查詢換行符
if (find) //如果地址不是NULL
*find = '\0'; //在此處放置一個空字元
else
while (getchar() != '\n')
continue; //處理輸入行中剩餘的字串
}
return ret_val;
}
執行結果: