Question

So, what I'm trying to do, is have the user search for a cheese and having it display it on the screen. I'm having trouble with the latter. I cant seem to display the string, but my code still runs. Here is my code:

#include<stdio.h>
#include<string.h>

    char cheeses[][20] = {
        "Cheddar",
        "White Cheddar",
        "Colby Jack",
        "Gouda",
        "Blue Cheese",
        "Gorgonzola",
        "Asiago", 
        "Limburger",
        "Feta",
        "Brie",
        "Goat",
    };

        void find_cheese(const char *search_for)
    {
        int i;
        for (i = 0; i < 5; i++) {
            if (strstr(cheeses[i], search_for))
                printf("Cheese %i: '%s'\n", i, cheeses[i]);
        }
    }

int main()
    {
        char search_for[20];
        printf("Search for: ");
        fgets(search_for, 20, stdin);
        find_cheese(search_for);
        return 0;
    }

So what do I do in this case. I want it so that you can type in, "Lim," and have it display Limburger (in the future it will be able to display info on the cheese). How will I do this?

Was it helpful?

Solution

It looks okay, but you only search through the 5 first, and Limburger is too close to the end of the list.

This type of code is better to solve with a "sentinel", i.e. a special marker that is used to signify that the list has ended. For strings, you can represent the array as an array of pointers to strings rather than a fixed-size array, and then using NULL as the sentinel is pretty natural.

The array would become:

const char *cheeses[] = { "Cheddar", "White Cheddar", "Colby Jack",
          /* ... rest of the cheeses ... */
          NULL
};

then you can write the search loop like so:

int i;

for( i = 0; cheeses[i] != NULL; ++i )
{
  /* Test and handling code here, against cheeses[i] just like before. */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top