C语言—菜单浏览

作者:追风剑情 发布于:2019-9-11 21:15 分类:C

示例:菜单小程序

  1. //Visual Studio中加上这句才可以使用scanf()
  2. //否则只能使用scanf_s()
  3. #define _CRT_SECURE_NO_WARNINGS
  4. #include <stdio.h>
  5. #include <stdbool.h>
  6.  
  7. char get_choice(void);
  8. char get_first(void);
  9. int get_int(void);
  10. void count(void);
  11.  
  12. //argc: 参数个数 argv[]: 参数数组
  13. int main(int argc, char *argv[])
  14. {
  15. int choice;
  16. void count(void);
  17.  
  18. while ((choice = get_choice()) != 'q')
  19. {
  20. switch (choice)
  21. {
  22. case 'a':
  23. printf("Buy low, sell high.\n");
  24. break;
  25. case 'b':
  26. putchar('\a');//发出蜂鸣声
  27. break;
  28. case 'c':
  29. count();
  30. break;
  31. default:
  32. printf("Program error!\n");
  33. break;
  34. }
  35. }
  36. printf("Bye.\n");
  37.  
  38. system("pause");
  39. return 0;
  40. }
  41.  
  42. void count(void)
  43. {
  44. int n, i;
  45. printf("Count how far? Enter an integer:\n");
  46. n = get_int();
  47. for (i = 1; i <= n; i++)
  48. printf("%d\n", i);
  49. // 处理输入的多余字符,包括回车
  50. while (getchar() != '\n')
  51. continue;
  52. }
  53.  
  54. char get_choice(void)
  55. {
  56. int ch;
  57. printf("Enter the letter of your choice:\n");
  58. printf("a. advice b. bell\n");
  59. printf("c. count q. quit\n");
  60. ch = get_first();
  61. while ((ch < 'a' || ch > 'c') && ch != 'q')
  62. {
  63. printf("Please respond with a, b, c, or q.\n");
  64. ch = get_first();
  65. }
  66. return ch;
  67. }
  68.  
  69. char get_first(void)
  70. {
  71. int ch;
  72. ch = getchar();
  73. while (getchar() != '\n')
  74. continue;
  75. return ch;
  76. }
  77.  
  78. int get_int(void)
  79. {
  80. int input;
  81. char ch;
  82. while (scanf("%d", &input) != 1)
  83. {
  84. while ((ch = getchar()) != '\n')
  85. putchar(ch); //处理错误输入
  86. printf(" is not an integer.\nPlease enter an ");
  87. printf("integer value, such as 25, -178, or 3: ");
  88. }
  89. return input;
  90. }

运行测试
1111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号