这里直接举个栗子了
使用命令字典的方式:
命令字典(Command Dictionary):命令字典是一种更灵活的菜单设计方法,通过使用函数指针和关联的命令字符串来实现。你可以创建一个包含命令字符串和对应函数指针的结构体数组,在用户输入后,遍历数组并查找匹配的命令字符串,然后调用对应的函数执行相应操作。这种方法适用于较大规模和可扩展的菜单,可以方便地添加、删除和修改菜单选项。
下面先简单介绍一下命令字典:
在C语言中,命令字典可以通过结构体数组和函数指针来实现。下面对命令字典的C语言语法进行详解:
1.定义命令结构体(Command struct):
命令结构体用于存储命令字符串和对应的函数指针。
typedef struct {
const char* command;
void (*function)();
} Command;
- const char* command:命令字符串,在该例子中使用C语言的字符串表示。
- void (*function)():函数指针,指向对应命令的处理函数。这里使用了无返回值且无参数的函数指针,如果需要传递参数或有返回值,可根据具体情况修改函数指针的类型。
2.定义命令字典数组(Command array):
命令字典数组由多个命令结构体组成,每个结构体包含一个命令字符串和对应的函数指针。
Command commandDictionary[] = {
{"command1", command1},
{"command2", command2},
{"command3", command3},
// 添加更多命令...
};
3.定义命令处理函数(Command function):
命令处理函数是实际处理具体命令操作的函数,在命令字典中与命令结构体的函数指针相对应。
void command1() {
// 处理Command 1的具体操作
}
void command2() {
// 处理Command 2的具体操作
}
void command3() {
// 处理Command 3的具体操作
}
// 添加更多命令处理函数...
4.调用命令字典执行对应操作:
在菜单循环中,根据用户输入的命令字符串遍历命令字典,找到匹配的命令后使用对应函数指针调用命令处理函数。
for (int i = 0; i < sizeof(commandDictionary) / sizeof(commandDictionary[0]); i++) {
if (strcmp(input, commandDictionary[i].command) == 0) {
// 找到匹配的命令,调用对应的命令处理函数
commandDictionary[i].function();
isValidCommand = 1;
break;
}
}
根据以上命令字典的简单介绍下面我们来简单实现一下基于对象字典的C语言菜单:
下面是简单的C语言例子,希望对你有帮助
#include <stdio.h>
#include <string.h>
// 命令处理函数声明
void command1();
void command2();
void command3();
void command4();
// 命令结构体
typedef struct {
const char* command; // 命令字符串
void (*function)(); // 对应的命令处理函数
} Command;
// 命令数组
Command commandDictionary[] = {
{"command1", command1},
{"command2", command2},
{"command3", command3},
{"command4", command4}
};
int main() {
char input[20];
int isValidCommand = 0;
printf("Welcome to the command dictionary menu!\n");
while (1) {
printf("\nEnter a command: ");
scanf("%s", input);
// 遍历命令字典,查找匹配的命令
for (int i = 0; i < sizeof(commandDictionary) / sizeof(commandDictionary[0]); i++) {
if (strcmp(input, commandDictionary[i].command) == 0) {
// 找到匹配的命令,调用对应的命令处理函数
commandDictionary[i].function();
isValidCommand = 1;
break;
}
}
if (!isValidCommand) {
printf("Invalid command! Please try again.\n");
}
isValidCommand = 0; // 重置标志位
}
return 0;
}
// 实际的命令处理函数实现
void command1() {
printf("Executing Command 1...\n");
// 执行Command 1的具体操作
}
void command2() {
printf("Executing Command 2...\n");
// 执行Command 2的具体操作
}
void command3() {
printf("Executing Command 3...\n");
// 执行Command 3的具体操作
}
void command4() {
printf("Executing Command 4...\n");
// 执行Command 4的具体操作
}
这样是不是就比较简单的就能实现菜单切换以及内容的增加删除修改。