示例:菜单小程序
//Visual Studio中加上这句才可以使用scanf() //否则只能使用scanf_s() #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdbool.h> char get_choice(void); char get_first(void); int get_int(void); void count(void); //argc: 参数个数 argv[]: 参数数组 int main(int argc, char *argv[]) { int choice; void count(void); while ((choice = get_choice()) != 'q') { switch (choice) { case 'a': printf("Buy low, sell high.\n"); break; case 'b': putchar('\a');//发出蜂鸣声 break; case 'c': count(); break; default: printf("Program error!\n"); break; } } printf("Bye.\n"); system("pause"); return 0; } void count(void) { int n, i; printf("Count how far? Enter an integer:\n"); n = get_int(); for (i = 1; i <= n; i++) printf("%d\n", i); // 处理输入的多余字符,包括回车 while (getchar() != '\n') continue; } char get_choice(void) { int ch; printf("Enter the letter of your choice:\n"); printf("a. advice b. bell\n"); printf("c. count q. quit\n"); ch = get_first(); while ((ch < 'a' || ch > 'c') && ch != 'q') { printf("Please respond with a, b, c, or q.\n"); ch = get_first(); } return ch; } char get_first(void) { int ch; ch = getchar(); while (getchar() != '\n') continue; return ch; } int get_int(void) { int input; char ch; while (scanf("%d", &input) != 1) { while ((ch = getchar()) != '\n') putchar(ch); //处理错误输入 printf(" is not an integer.\nPlease enter an "); printf("integer value, such as 25, -178, or 3: "); } return input; }