What is wrong with this C code?

I find out using fgets() is the cause of error in getting user input and use this string on strstr() function.

By perform some good advice from Blastfurnace, woz and other guys in Question comment section I can fix this problem.

Code

#include <stdio.h>
#include <stdlib.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;
    char * pch;
    int flag = 0;

    for(i=0;i<5;i++){
        pch = strstr(tracks[i], search_for);
        if (pch){
            printf("find in Track   %i: '%s'\n", i, tracks[i]);
            flag = 1;//find

        }
    }
    
    if (flag == 0)// not found
        printf("Track Not found\n");

}

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

Leave a Comment