menu_sleect函数用法
时间: 2023-06-14 07:03:00 浏览: 64
`menu_select` 函数通常用于在控制台中显示一个菜单,让用户可以从中选择一个选项。以下是 `menu_select` 函数的使用方法:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int menu_select(char *menu[], int menu_size);
int main() {
char *menu[] = {"Option 1", "Option 2", "Option 3", "Option 4"};
int menu_size = sizeof(menu) / sizeof(menu[0]);
int choice = menu_select(menu, menu_size);
printf("You selected option %d: %s\n", choice, menu[choice - 1]);
return 0;
}
int menu_select(char *menu[], int menu_size) {
int choice = 0;
do {
printf("Please select an option:\n");
for (int i = 0; i < menu_size; i++) {
printf("%d. %s\n", i + 1, menu[i]);
}
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice < 1 || choice > menu_size) {
printf("Invalid choice. Please try again.\n");
}
while (getchar() != '\n'); // Clear input buffer
} while (choice < 1 || choice > menu_size);
return choice;
}
```
在上面的示例中,`menu_select` 函数接受一个字符串数组 `menu` 和它的大小 `menu_size` 作为参数。`menu` 数组包含菜单选项的字符串,而 `menu_size` 是菜单选项的数量。
`menu_select` 函数使用一个 `do-while` 循环来显示菜单并读取用户的选择。如果用户输入的选择无效,则会提示用户重新输入。
主函数中,我们使用 `menu_select` 函数来展示菜单,并打印出用户选择的选项。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![jpg](https://img-home.csdnimg.cn/images/20210720090814.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)