Linux下的c程序---enum、switch、strcmp

最近开始学习Linux下c的程序设计,根据自己的学习过程,将要发一系列的文章和大家一起讨论。

 

#include <stdio.h>
#include <string.h>    // for strcmp()
#include <stdbool.h>   // C99 feature

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):"); // puts() 输出函数
    while (gets(choice) != 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)  //使用switch分叉控制流程
             {
                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 is 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("Goodbye!");
    return 0;
}

你可能感兴趣的:(switch)