B Narsimulu
B Narsimulu

Reputation: 47

every time strstr() function is returning false. when i pass any input always function is returning false

I am trying to search is there any track available in tracks array. When I gave any input always strstr() function is returning false. If I use else block, every time else block is executing.

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

    // function to search the track with entered search string //
    void find_track(char search_for[]) {
        int i;
        for (i = 0; i < 5; i++) {
            /** this if condition is returning false every time */
            if (strstr(tracks[i], search_for)){
            printf("Track %i: '%s'\n", i, tracks[i]);
            }/**else{
                printf("some thing went wrong @ %i\n", i);
            }**/
        }
    }



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

Input:

gcc test.c -o test && test

Search for : with

expected result : Track 2:'Dancing with a Dork'

please help me.

Upvotes: 1

Views: 163

Answers (1)

R Sahu
R Sahu

Reputation: 206667

fgets reads the newline character as well. You need to remove it from search_for before passing it to find_track.

See Removing the newline from fgets.

Upvotes: 3

Related Questions