【发布时间】:2016-08-31 06:27:56
【问题描述】:
基本上我想输入一个文本字符串,如果它与结构上的字符串(*cmd_name)匹配,程序将调用并执行与其对应的函数。这是我的尝试:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void new_cmd()
{
printf("You entered new_cmd function!");
}
void close_cmd()
{
printf("You entered close_cmd function!");
}
void open_cmd()
{
printf("You entered open_cmd function!");
}
void close_all_cmd()
{
printf("You entered the close_all_cmd function!");
}
struct{
char *cmd_name;
void (*cmd_pointer)(void); //variable of a pointer to a function
}file_cmd[]= { {"new", new_cmd},
{"open", open_cmd},
{"close", close_cmd},
{"close all", close_all_cmd}};
int main()
{
int i;
char my_string[15];
scanf("%s",my_string);
for(i=0; i<4;i++)
if(file_cmd[i].cmd_name == my_string) //matching the string
{
file_cmd[i].cmd_pointer(); //possible mistake here, trying to open the function
break;
}
return 0;
}
每当我对此进行测试并在命令行“new”或任何字符串上写入时,程序根本不会执行并退出。
【问题讨论】:
-
==无法比较字符串,只能比较地址。使用strcmp。 SO上有很多类似的问题,先搜索一下。
标签: c string variables pointers structure