menuette.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* menuette.c -- menu techniques */
  2. #include <stdio.h>
  3. char get_choice(void);
  4. char get_first(void);
  5. int get_int(void);
  6. void count(void);
  7. int main(void)
  8. {
  9. int choice;
  10. void count(void);
  11. while ( (choice = get_choice()) != 'q')
  12. {
  13. switch (choice)
  14. {
  15. case 'a' : printf("Buy low, sell high.\n");
  16. break;
  17. case 'b' : putchar('\a'); /* ANSI */
  18. break;
  19. case 'c' : count();
  20. break;
  21. default : printf("Program error!\n");
  22. break;
  23. }
  24. }
  25. printf("Bye.\n");
  26. return 0;
  27. }
  28. void count(void)
  29. {
  30. int n,i;
  31. printf("Count how far? Enter an integer:\n");
  32. n = get_int();
  33. for (i = 1; i <= n; i++)
  34. printf("%d\n", i);
  35. while ( getchar() != '\n')
  36. continue;
  37. }
  38. char get_choice(void)
  39. {
  40. int ch;
  41. printf("Enter the letter of your choice:\n");
  42. printf("a. advice b. bell\n");
  43. printf("c. count q. quit\n");
  44. ch = get_first();
  45. while ( (ch < 'a' || ch > 'c') && ch != 'q')
  46. {
  47. printf("Please respond with a, b, c, or q.\n");
  48. ch = get_first();
  49. }
  50. return ch;
  51. }
  52. char get_first(void)
  53. {
  54. int ch;
  55. ch = getchar();
  56. while (getchar() != '\n')
  57. continue;
  58. return ch;
  59. }
  60. int get_int(void)
  61. {
  62. int input;
  63. char ch;
  64. while (scanf("%d", &input) != 1)
  65. {
  66. while ((ch = getchar()) != '\n')
  67. putchar(ch); // dispose of bad input
  68. printf(" is not an integer.\nPlease enter an ");
  69. printf("integer value, such as 25, -178, or 3: ");
  70. }
  71. return input;
  72. }