【孙剑峰 SA16225264 + 《软件工程(C编码实践篇)》MOOC课程作业http://mooc.study.163.com/course/USTC-1000002006】
代码地址: http://git.shiyanlou.com/csxiaoyao/shiyanlou_cs122/src/master/lab3
通过设计简单的命令行菜单小程序,了解并掌握程序内部模块化设计的思想,实现菜单数据存储与菜单业务逻辑的分离。
用一个静态链表来存储可变化的菜单命令及其对应函数,在主函数中实菜单命令逻辑。 在一个头文件中定义链表数据结构及其操作原型,并在相应源文件中实现其操作;然后在主函数源文件中实现菜单命令。
实验代码如下:
typedef struct DataNode {
char* cmd;
char* desc;
int(*handler)();
struct DataNode *next;
}tDataNode;
tDataNode* FindCmd(tDataNode *head, char *cmd);
int ShowAllCmd(tDataNode * head);
#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"
tDataNode* FindCmd(tDataNode *head, char *cmd) {
if (head == NULL || cmd == NULL)
return NULL;
tDataNode *p = head;
while (p != NULL) {
if (strcmp(cmd, p->cmd) == 0)
return p;
p = p->next;
}
return NULL;
}
int ShowAllCmd(tDataNode *head) {
printf("Menu list:\n");
tDataNode *p = head;
while (p != NULL) {
printf("%s - %s\n", p->cmd, p->desc);
p = p->next;
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"
#define CMD_MAX_LEN 128
#define DESC_LEN 1024
#define CMD_NUM 10
int Help();
int Quit();
/*menu program*/
static tDataNode head[] = {
{ "help","This is a help cmd.",Help,&head[1] },
{ "version","menu program v2.0.",NULL,&head[2] },
{ "quit","Quit form menu.",Quit,NULL }
};
int main() {
/*cmd line begin*/
while (1) {
char cmd[CMD_MAX_LEN];
printf("Please input a cmd:>");
scanf("%s", cmd);
tDataNode* p = FindCmd(head, cmd);
if (p == NULL) {
printf("This is a wrong cmd!");
continue;
}
printf("%s - %s\n", p->cmd, p->desc);
if (p->handler != NULL)
p->handler();
}
return 0;
}
int Help() {
ShowAllCmd(head);
return 0;
}
int Quit() {
exit(0);
}
软件=程序+软件工程,程序=算法+数据结构
通过本次实验,我主要有以下几个方面的收获:
学习时间 97分钟
操作时间 12分钟
按键次数 183次
实验次数 2次
报告字数 2390字
是否完成 完成