cstrstr

strstr not returning desired result


Can you identify the error in this code, it's not being able to print the song even though I pass the valid parameters to find

#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 askedSong[80];
    printf("%s", "Hey buddy, what is the good one today? ");
    fgets(askedSong, sizeof(askedSong), stdin);
    find_track(askedSong);
    return 0;
}

Solution

  • fgets leaves the newline in the string. Easy fix:

    fgets(askedSong, sizeof(askedSong), stdin);
    askedSong[strcspn(askedSong, "\n")] = 0;