#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define ERROR_SUCCESS 0
#define ERROR_FAILED -1
#define MENU_NUM_MAX 5
typedef enum menu
{
MENU_UNSPEC,
MENU_ADD,
MENU_SUB,
MENU_EXIT,
MENU_MAX
}MENU_E;
static void DisplayMenu(void)
{
printf("\r----Menu----\n\
\r1.Add\n\
\r2.Sub\n\
\r3.Exit\n\
\r------------\n");
}
static int GetChoice(MENU_E *choice)
{
printf("Please input your choice:\n");
scanf("%d", choice);
if((*choice <= MENU_UNSPEC) || (*choice >= MENU_MAX))
{
return ERROR_FAILED;
}
return ERROR_SUCCESS;
}
static int Add(void)
{
int augend = 0; //被加数
int addend = 0; //加数
printf("请输入被加数、加数:\n");
scanf("%d, %d", &augend, &addend);
return (augend + addend);
}
static int Sub(void)
{
int subtrahend = 0; //被减数
int subtractor = 0; //减数
printf("请输入被减数、减数:\n");
scanf("%d, %d", &subtrahend, &subtractor);
return (subtrahend - subtractor);
}
static int Exit(void)
{
return ERROR_SUCCESS;
}
/* 函数指针。该函数参数为空,返回值为整型。 */
typedef int (* OPERATE_PF)(void);
typedef struct cmd_operate
{
MENU_E cmd;
OPERATE_PF func;
}CMD_OPERATE_S;
static CMD_OPERATE_S operate[MENU_NUM_MAX] =
{
{MENU_UNSPEC, NULL},
{MENU_ADD, Add},
{MENU_SUB, Sub},
{MENU_EXIT, Exit},
{MENU_MAX, NULL}
};
void main(void)
{
OPERATE_PF pfFunc = NULL;
MENU_E choice = MENU_UNSPEC;
int errCode = ERROR_SUCCESS;
int result = 0;
do
{
DisplayMenu();
errCode = GetChoice(&choice);
if(ERROR_SUCCESS == errCode)
{
pfFunc = operate[choice].func;
result = pfFunc();
if(MENU_EXIT != choice)
{
printf("The result is : %d\n", result);
}
}
if(ERROR_SUCCESS != errCode)
{
printf("Input parameter invalid.\n");
}
}while(MENU_EXIT != choice);
return;
}
跳转表实例(二)
最新推荐文章于 2022-04-03 22:39:56 发布