跳转表实例(二)

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值