enum的用法

作者:追风剑情 发布于:2020-3-13 13:29 分类:C

示例


  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h> //C99特性
  5. #include <string.h>
  6.  
  7. char* s_gets(char* st, int n);
  8.  
  9. enum spectrum {red, orange, yellow, green, blue, violet};
  10. const char* colors[] = {"red", "orange", "yellow", "green", "blue","violet"};
  11. #define LEN 30
  12.  
  13. /* C允许同名,C++不允许. 例如下面代码:*/
  14. struct rect { double x; double y; };
  15. int rect;
  16.  
  17. int main(int argc, char* argv[])
  18. {
  19. char choice[LEN];
  20. enum spectrum color;
  21. bool color_is_found = false;
  22.  
  23. puts("Enter a color (empty line to quit):");
  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. {
  37. switch (color)
  38. {
  39. case red:
  40. puts("Roses are red.");
  41. break;
  42. case orange:
  43. puts("Poppies are orange.");
  44. break;
  45. case yellow:
  46. puts("Sunflowers are yellow.");
  47. break;
  48. case green:
  49. puts("Grass are green.");
  50. break;
  51. case blue:
  52. puts("Bluebells are blue.");
  53. break;
  54. case violet:
  55. puts("Violets are violet.");
  56. break;
  57. default:
  58. break;
  59. }
  60. }
  61. else
  62. {
  63. printf("I don't know about the color %s.\n", choice);
  64. }
  65. color_is_found = false;
  66. puts("Next color, please (empty line to quit):");
  67. }
  68. puts("Goodbye!");
  69.  
  70. system("pause");
  71. return 0;
  72. }
  73.  
  74.  
  75. // 自己实现读取函数
  76. char* s_gets(char* st, int n)
  77. {
  78. char* ret_val;
  79. int i = 0;
  80. ret_val = fgets(st, n, stdin);
  81. if (ret_val) //即,ret_val != NULL
  82. {
  83. while (st[i] != '\n' && st[i] != '\0')
  84. i++;
  85. if (st[i] == '\n')
  86. st[i] = '\0';
  87. else
  88. while (getchar() != '\n')
  89. continue;
  90. }
  91. return ret_val;
  92. }


运行测试

1111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号