'When given a string as an argument, how may I search an array of structures for a matching string?

I am having difficulties trying to debug the behavior of my code. I am working on a function that, given a string, searches a given array of structures for a matching command name and then calls the function associated with that name. If the string argument passed to do_file_menu() specifies a menu option not in the array file[ ], the function should print "Invalid menu option." to the screen and return.

When I only use this code:

void do_file_menu(char *name)
{
  int i;
  int len = ( sizeof(file)/sizeof(file[0]) );
  for (i = 0; i < len; i++){
    if (!strcmp(file[i].cmd_name , name)){
      file[i].cmd_ptr();
      break;
    }
  }
 }

For the strings that are within the array file[] i get the following (desired) output:

Created new file.
Opened file.
File saved.
Printing file...
Goodbye.

However, when I attempt to code the "invalid menu option" case as such:

void do_file_menu(char *name)
{
  int i;
  int len = ( sizeof(file)/sizeof(file[0]) );
  for (i = 0; i < len; i++){
    if (!strcmp(file[i].cmd_name , name)){
      file[i].cmd_ptr();
      break;
    }
    else if (strcmp(file[i].cmd_name , name)){
      printf("Invalid menu option.\n");
      break;
    }
  }
 }

The output is:

Created new file.
Invalid menu option.
Invalid menu option.
Invalid menu option.
Invalid menu option.
Invalid menu option.
Invalid menu option.
Invalid menu option.

I am out of ideas. For further reference, there are 8 calls in total to the do_file_menu() function. 5 of the calls are within the array file[], and 2 are not.

Final, correct output should be:

Created new file.
Opened file.
File saved.
Printing file...
Goodbye.
Invalid menu option.
Invalid menu option.
c


Solution 1:[1]

You need to put the "not found" condition outside of the loop, after you've checked all possible strings in the list and still haven't found the target name:

#include <stdbool.h>
...
void do_file_menu(char *name)
{
  int i;
  bool found = false;
  int len = ( sizeof(file)/sizeof(file[0]) );
  for (i = 0; i < len; i++){
    if (!strcmp(file[i].cmd_name , name)){
      file[i].cmd_ptr();
      found = true;
      break;
    }
  }
  if (!found)
    printf("Invalid menu option.\n");
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 paulsm4