1

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.

2

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.