通过结构体和函数指针进行菜单操作的一个实例2007-12-17 13:03:00
前天帮同学写了一个菜单,感觉对不太了解函数指针的同学来说有点借鉴意义,原程序如下,可以直接放在vc++6.0环境下运行,移植到单片机上也是非常的简单的!
程序如下:
\\-------------------------------------------------------------------------
#i nclude<stdio.h>
void fun0(void){
printf("\tYou are right!\n\tHere is fun0()!\n");
}
void fun1(void){
printf("\tYou are right!\n\tHere is fun1()!\n");
}
void fun2(void){
printf("\tYou are right!\n\tHere is fun2()!\n");
}
void fun3(void){
printf("\tYou are right!\n\tHere is fun3()!\n");
}
void fun4(void){
printf("\tYou are right!\n\tHere is fun4()!\n");
}
void fun5(void){
printf("\tYou are right!\n\tHere is fun5()!\n");
}
struct { //声明一个结构体
void (*fun)(void); //声明一个函数指针
char *tip;
}CmdTip[] = { //结构体初始化
{ fun0, "fun0() test"},
{ fun1, "fun1() test"},
{ fun2, "fun2() test"},
{ fun3, "fun3() test"},
{ fun4, "fun4() test"},
{ fun5, "fun5() test"},
{ 0, 0}
};
void main(void){
int idx,i;
while(1){
printf("\n\n\n\t=====================\n");
printf("\t| 菜单 |\n");
printf("\t---------------------\n");
for(i=0; CmdTip.fun!=0; i++)
printf("\t| %2d: %s |\n", i, CmdTip.tip);
printf("\t=====================\n\n");
printf("请输入一个菜单编号并按ENTER键:");
scanf("%d",&idx);
if(idx<i)
{
(*CmdTip[idx].fun)();
}
else printf("\t你输入了一个错误的数字:%d;请重新输入!\n", idx);
}
}
\\-------------------------------------------------------------------------
用户377235 2013-12-15 10:50