Basically I want to input a string of text and if it matches with the string on the structure (*cmd_name), the program will then call and execute the function that corresponds to it. Here's my attempt:
#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;
}
Whenever I test this and write on the command line "new" or any string, the program doesn't execute at all and exits.
You can not compare strings using ==
, you have to use strcmp()
.
That said, scanf("%s",my_string);
should better be scanf("%14s",my_string);
to avoid buffer overlow by longer-than-expected input. Also, you should always check the return value of scanf()
to ensure success.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.