#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;
}
跳轉表實例(二)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.