用c语言设计一个菜单
时间: 2024-10-02 11:02:13 浏览: 33
在C语言中,设计一个简单的菜单通常涉及创建一个循环结构,允许用户根据预设的选择进行交互。下面是一个基本的控制台应用示例,它包含几个选项:
```c
#include <stdio.h>
#include <conio.h> // 包含用于键盘输入的库
// 定义菜单选项及其对应的函数指针
typedef void (*menu_func)(void);
// 菜单函数列表
typedef struct {
char *option;
menu_func func;
} MenuOption;
static MenuOption menu_options[] = {
{"1. 显示欢迎消息", display_welcome},
{"2. 计算两数之和", add_numbers},
{"3. 退出程序", exit_program},
};
// 菜单项函数实现
void display_welcome() {
printf("欢迎使用我的程序!\n");
}
void add_numbers() {
int a, b;
printf("请输入两个数字: ");
scanf("%d %d", &a, &b);
printf("它们的和是: %d\n", a + b);
}
void exit_program() {
printf("感谢您的使用,再见!\n");
getch(); // 等待用户按下任意键再退出
exit(0);
}
int main() {
int choice;
while (true) {
printf("\n请选择操作:\n");
for (size_t i = 0; i < sizeof(menu_options) / sizeof(MenuOption); ++i) {
printf("%d. %s\n", i + 1, menu_options[i].option);
}
printf("0. 退出程序\n");
// 获取用户输入并转换为整数
printf("Enter your choice: ");
scanf("%d", &choice);
// 验证输入是否有效
if (choice >= 0 && choice <= (int)sizeof(menu_options)) {
menu_options[choice - 1].func();
} else {
printf("无效选择,程序继续运行...\n");
}
// 询问用户是否继续
printf("是否继续? (y/n): ");
getchar(); // 消耗回车字符
if (getchar() != 'y' && getchar() != 'Y') { // 输入不是'y'或'n'
break;
}
}
return 0;
}
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)