求解一个关于typedef void (*msg)(void)的问题
void hello()
{
printf("hello\n");
}
void bye()
{
printf("goodbye\n");
}
typedef void (*msg)(void)
typedef void (*msg)(void);
void hello(void){printf("hello\n");}
void bye(void){printf("bye\n");}
int getId(char ch)
{
if(ch == 'h')return 0;
else if(ch=='b')return 1;
return 2;
}
void printX(int id);
//这么处理行不
void printXbychar(char ch)
{
int id =getId(ch);
if(id!=2) printX(id);
}
void printX(int id)
{
msg words[3]={&hello,&bye};
msg m=map[id];
(*m)();
}
//函数名是存在配置文件k2fun.cfg中的,如下:
//h=hello
//b=bye
//想要在main()中通过输入一个字母,并读取配置文件,来识别字母对应的函数名,并调用相应的函数。
#include <stdio.h>
#include <string.h>
#define MAXFUNNAMELEN 30
#define MAXFUNS 100
void unknown() {
printf("unknown\n");
}
void hello() {
printf("hello\n");
}
void bye() {
printf("goodbye\n");
}
FILE *f;
typedef void (*pfun)(void);
pfun funs[MAXFUNS];
char funnames[MAXFUNS][MAXFUNNAMELEN];
int i,n,L;
char c;
char ln[1+1+MAXFUNNAMELEN+1+1];
int main() {
funs[0]=hello; strcpy(funnames[0],"hello");
funs[1]=bye; strcpy(funnames[1],"bye");
for (i=2;i<MAXFUNS;i++) {
funs[i]=unknown; strcpy(funnames[i],"unknown");
}
f=fopen("k2fun.cfg","r");
if (NULL==f) {
printf("Can not open file k2fun.cfg!\n");
return 1;
}
printf("Input a char:");fflush(stdout);
rewind(stdin);
scanf("%c",&c);
n=0;
while (1) {
if (NULL==fgets(ln,1+1+MAXFUNNAMELEN+1+1,f)) break;
n++;
while (1) {
L=strlen(ln)-1;
if ('\n'==ln[L]
[解决办法]
' '==ln[L]) ln[L]=0;
else break;
}
if ('='!=ln[1]) {
printf("Format Error at line %d:%s\n",n,ln);
} else {
if (c==ln[0]) {
for (i=0;i<MAXFUNS;i++) {
if (0==strcmp(ln+2,funnames[i])) {
funs[i]();
fclose(f);
return 0;
}
}
}
}
}
fclose(f);
printf("Can not find function of key '%c'!\n",c);
return 2;
}
//C:\test>test
//Input a char:a
//Can not find function of key 'a'!
//
//C:\test>test
//Input a char:h
//hello
//
//C:\test>test
//Input a char:b
//goodbye
//
(1)先定义一个函数名->函数的映射
typedef void (*pFun)(void);
map<string, pFun> nameFunMap;
nameFunMap.insert(make_pair("hello", &hello));
nameFunMap.insert(make_pair("bye", &bye));
(2)再定义一个缩写->函数名的映射
map<char, string> abbrNameMap;
char line[MAX], *p;
fp = fopen(initFilePath, "r");
while(fgets(line, MAX, fp)){
if((p = strchr(line, '=')) && p-line == 1){//你用的是一个字母的缩写
abbrNameMap.insert(make_pair(line[0], string(*(p+1))));
}
}
(3)根据输入的缩写得到函数名,根据函数名调用函数
map<char, string>::iterator abbrNameIter;
map<string, pFun>::iterator nameFunIter;
c = getchar();
abbrNameIter = abbrNameMap.find(c);//根据输入的缩写得到函数名
if(abbrNameIter != abbrNameMap.end()){
nameFunIter = nameFunMap.find(abbrNameIter->second);//根据函数名得到函数地址
if(nameFunIter != nameFunMap.end()) *(nameFunIter->second);//调用函数
}