"strstr()" function is not locating what I expect

Asked

Viewed 346 times

0

#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",
    "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;
}

1 answer

2


By the way you are reading the text (which is not the most advisable) it is placing the end-of-line character within the string, there will search for the text c/ the end of line and will not find. You need to close the string when you find this character, so the search will be done only in the text. For this you need to add this code before using the string:

search_for[strcspn(search_for, "\n")] = 0;

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.