Search code examples
cfgetsstrstr

strstr() function in C programming


I am learning C from the book Head First C, and I tried one of the examples, and despite having the same code, my code won't run like the example in the book. The code aims to use the strstr() function to find a string within another string, but after running my code, it only asks for my input, and displays "Program ended with exit code: 0"

Below is my code:

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

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "Newark, Newark - a wonderful town",
    "Dancing with a Dork",
    "From here to maternity",
    "The girl from Iwo Jima",
};

void find_track(char search_for[])
{
    int i;
    for (i=0; i<5; i++) {
        if(strstr(tracks[i],search_for))
            printf("Track %i: '%s'\n", i, tracks[i]);
    }
}

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

The result after running the code is:

Search for: (my input)
Program ended with exit code: 0

Help!


Solution

  • That code is wrong; fgets reads a full line, leaving the newline character in the target buffer (unless you provided exactly 79 characters). For that reason, find_track will look for a string with a terminating newline, which of course cannot be found.

    A possible fix can be to remove the last character from the input string, just after the fgets.

    if(*search_for) search_for[strlen(search_for) -1] = 0;
    

    or to use a different input function, which does not read the newline.