Search code examples
cstrstr

C strstr issue, Returning 0 even when should be 1?


Spent a while trying to debug this. Strstr always returns 0, even when I pass an argument like "town" that should make sense and print 1. What am I doing wrong here?

#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)) // Always 0 never 1?
            printf("Track %i: '%s'\n", i, tracks[i]);
    }
}

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

Solution

  • Function fgets includes in the string the new line character'\n', that corresponds to the pressed key Enter.

    You should remove it before calling function find_track For example

    size_t n = strlen( search_for );
    if ( n && search_for[n-1] == '\n' ) search_for[--n] = '\0';
    

    Take into account that it would be better to write the function such a way that it would not deal with global arrays that is that it would be more generic. The both arrays including the size of the global array should be its parameters