enum.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* enum.c -- uses enumerated values */
  2. #include <stdio.h>
  3. #include <string.h> // for strcmp(), strchr()
  4. #include <stdbool.h> // C99 feature
  5. char * s_gets(char * st, int n);
  6. enum spectrum {red, orange, yellow, green, blue, violet};
  7. const char * colors[] = {"red", "orange", "yellow",
  8. "green", "blue", "violet"};
  9. #define LEN 30
  10. int main(void)
  11. {
  12. char choice[LEN];
  13. enum spectrum color;
  14. bool color_is_found = false;
  15. puts("Enter a color (empty line to quit):");
  16. while (s_gets(choice, LEN) != NULL && choice[0] != '\0')
  17. {
  18. for (color = red; color <= violet; color++)
  19. {
  20. if (strcmp(choice, colors[color]) == 0)
  21. {
  22. color_is_found = true;
  23. break;
  24. }
  25. }
  26. if (color_is_found)
  27. switch(color)
  28. {
  29. case red : puts("Roses are red.");
  30. break;
  31. case orange : puts("Poppies are orange.");
  32. break;
  33. case yellow : puts("Sunflowers are yellow.");
  34. break;
  35. case green : puts("Grass is green.");
  36. break;
  37. case blue : puts("Bluebells are blue.");
  38. break;
  39. case violet : puts("Violets are violet.");
  40. break;
  41. }
  42. else
  43. printf("I don't know about the color %s.\n", choice);
  44. color_is_found = false;
  45. puts("Next color, please (empty line to quit):");
  46. }
  47. puts("Goodbye!");
  48. return 0;
  49. }
  50. char * s_gets(char * st, int n)
  51. {
  52. char * ret_val;
  53. char * find;
  54. ret_val = fgets(st, n, stdin);
  55. if (ret_val)
  56. {
  57. find = strchr(st, '\n'); // look for newline
  58. if (find) // if the address is not NULL,
  59. *find = '\0'; // place a null character there
  60. else
  61. while (getchar() != '\n')
  62. continue; // dispose of rest of line
  63. }
  64. return ret_val;
  65. }