所谓转移表就是由——函数指针数组、枚举 两部分一起完成的。
例如:简易计算器的实现,如下:
<span style="font-family:Courier New;">#include<stdio.h>
int add(int a,int b);
int sub(int a,int b);
int mul(int a,int b);
int div(int a,int b);
enum opera{ADD,SUB,MUL,DIV}; //定义枚举类型
int main(void)
{
printf("input the operation string:\n");//输入的字符串如13+24、33-256、27*2、12/3 的形式
char ch;
int flag_a = 0,flag_op =0,flag_b =0;
int a = 0,b = 0,result = 0;
char opera = 0;
enum opera op;//定义符号枚举变量
int (*fun[4])(int,int)= {add,sub,mul,div};//定义函数指针数组
while(ch = getchar(),ch !='\n')
{
if(flag_op == 0 && ch >=48 && ch<=57)//操作数1
{
a = a*10 +(ch - '0');
flag_a = 1;
}
else if(flag_a == 1&& flag_op == 0&& (ch == '+'||ch == '-' ||ch == '*' ||ch == '/'))//运算符
{
opera = ch;
flag_op = 1;
}
else if(flag_op == 1 && ch >=48&&ch <=57)//操作数2
{
b = b*10+(ch -'0');
flag_b = 1;
}
else </span><span style="font-family: 'Courier New'; ">//意外之笔,输入格式不符合要求的字符 !</span><span style="font-family:Courier New;">
{
printf("the format you input is wrong !\n");
return -1;
}
}
if(flag_b == 0)//三部分没有输入完的 !
{
printf("the format you input is wrong !\n");
return -1;
}
switch(opera) //确定操作符
{
case '+': op = ADD; break;
case '-': op = SUB; break;
case '*': op = MUL; break;
case '/': op = DIV; break;
}
result = fun[op](a,b); //计算
printf("the result = %d\n",result);
return 0;
}
int add(int a,int b)
{
return a+b;
}
int sub(int a,int b)
{
return a-b;
}
int mul(int a,int b)
{
return a*b;
}
int div(int a,int b)
{
return a/b;
}</span>
分好几次不同输入下的执行的结果如下:
12+36
the result = 48
12-36
the result = -24
12*3
the result = 36
12/2
the result = 6
12
the format you input is wrong !
12-
the format you input is wrong !
12--3
the format you input is wrong !
-4
the format you input is wrong !
1a2-4
the format you input is wrong !