ykt1504834575963 + 《软件工程(C编码实践篇)》MOOC课程作业http://mooc.study.163.com/course/USTC-1000002006
本次实验以实验二的menu程序为原型,在完成类似功能的基础上进行改进。具体内容主要包括模块化编程等。
一、实验思路
1.观看学习云课堂相关视频,学会基本的模块化编码方法。
2.搭建实验环境,结合上次实验的menu程序,进行模块化修改。
3.运行程序,查漏补缺。
4.上传至代码库,完成实验报告。
二、实验过程
1.创建实验目录。
参照实验一、二过程,使用以下命令创建实验目录lab3及相关代码文件。
cd Code/shiyanlou_cs122
mkdir lab3
cd lab3
vi menu.c
vi linklist.h
vi linklist.c
2.代码编写。
根据实验要求,将代码的业务逻辑和数据存储分离,即将系统抽象为两个层级:菜单业务逻辑和菜单数据存储。具体来说,二者使用不同的源文件实现,即编写2个.c和一个.h作为接口文件。编码的同时需要主要上次实验中使用的代码规范。
menu.c的核心代码如下。与上次实验将命令写入main函数不同,此次将数据层独立出来,提高代码的复用性。
static tDateNode head[] =
{
{"help", "-------This is help cmd-------", help, &head[1]},
{"version", "-------Menu Program V1.0-------", NULL, &head[2]},
{"quit","-------Thanks for using-------", quit, NULL}
};
int main()
{
while(1)
{
char cmd[CMD_MAX_LEN];
printf("Please input a command > ");
scanf("%s", cmd);
tDateNode *p = findCmd(head, cmd);
if(p == NULL)
{
printf("-------Sorry, this is a wrong command-------\n");
continue;
}
printf("%s : %s \n", p->cmd,p->desc);
if(p->handler != NULL)
{
p->handler();
}
}
}
linklist.h核心代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct DateNode
{
char* cmd;
char *desc;
int (*handler)();
struct DateNode *next;
} tDateNode;
tDateNode *findCmd(tDateNode *head, char *cmd);
int showAllCmd(tDateNode *head);
linklist.c核心代码如下:
tDateNode *findCmd(tDateNode *head, char *cmd)
{
if(head == NULL || cmd == NULL)
{
return NULL;
}
tDateNode *p = head;
while(p != NULL)
{
if( !strcmp(p->cmd, cmd))
{
return p;
}
p = p->next;
}
return NULL;
}
int showAllCmd(tDateNode *head)
{
printf("\nHere are all commands: \n");
tDateNode *p = head;
while(p != NULL)
{
printf("%s : %s\n",p->cmd,p->desc);
p = p->next;
}
return 0;
}
3.编译及运行
本次实验需要同时编译多个文件,使用以下命令编译menu.c以及linklist.c,并运行可执行文件。
gcc linklist.c menu.c -o menu
./menu
可以看到实验结果如下图所示:
三、实验总结
本次实验较前两次实验又增加了一定的难度。首先,代码量有所增加,需要用到指针、链表等知识。由于近段时间使用java较多,c的知识有些遗忘。借此机会简单复习了指针的知识。同时,简单学习了怎样在c语言中,进行模块化的编码,把代码的业务逻辑和数据存储之间的分离,提高了代码的复用性。相信在之后的实验过程中,能继续学到更规范全面的编码方法。