咖啡机《软件工程(C编码实践篇)》MOOC课程作业http://mooc.study.163.com/course/USTC-1000002006
在版本库根目录下新创建一个目录lab3完成实验。
//定义菜单项数据结构
typedef struct DataNode
{
char* cmd;
char* desc;
void (*handler)();
struct DataNode *next;
} tDataNode;
//在菜单列表*head中寻找与cmd相符的菜单项
tDataNode* FindCmd(tDataNode *head, char *cmd);
//显示所有菜单项
int ShowAllCmd(tDataNode *head);
#include <stdlib.h>
#include <stdio.h>
#include <string.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(p->cmd, cmd) == 0)
{
return p;
}
p = p->next;
}
return NULL;
}
int ShowAllCmd(tDataNode *head)
{
tDataNode *p = head;
while(p != NULL)
{
printf("%s - %s\n", p->cmd, p->desc);
p = p->next;
}
return 0;
}
int main ()
{
char cmd[CMD_MAX_LEN];
info();
printf("Plesea input a command:\n");
while (1)
{
printf(">>>");
scanf("%s", cmd);
tDataNode *p = FindCmd(head, cmd);
if (p == NULL)
{
printf("Error: Wrong command!\n");
printf("Type 'info' for available commands.\n");
}
printf("%s - %s\n", p->cmd, p->desc);
if(p->handler != NULL)
{
p->handler();
}
}
return 0;
}
数据模块分离:
#define CMD_MAX_LEN 128
#define DESC_LEN 1024
#define CMD_NUM 20
static tDataNode head[] =
{
{"info", "Command Informations", info, &head[1]},
{"plus", "result of a + b", plus, &head[2]},
{"minus", "result of a - b", minus, &head[3]},
{"multiply", "result of a * b", multiply, &head[4]},
{"divide", "result of a / b", divide, &head[5]},
{"power", "result of a ^ b", power, &head[6]},
{"square", "result of square root of a", square, &head[7]},
{"factorial", "result of a!", factorial, &head[8]},
{"absolute", "result of |a|", absolute, &head[9]},
{"quit", "end this program", quit, NULL},
};
菜单命令包括以下9种:
- 介绍命令信息info()
- 加法运算plus()
- 减法运算minus()
- 乘法运算multiply()
- 除法运算divide()
- 幂运算power()
- 平方根运算square()
- 阶乘运算factorial()
- 绝对值运算absolute()
- 退出quit()
限制于报告篇幅,以上命令的具体实现代码就不在文中贴出,烦请移步github工程中查看。
https://github.com/973301529/se/tree/master/lab3
本次实验在上次实验的基础上更进一步,实现了代码的模块化,将代码的业务逻辑和数据存储分离。模块化有利于代码的修改、阅读,以后要将模块化的思想应用到实际的工作中去。