1

I was making a program to search a track from a list of tracks by getting an input string from user.

#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, m = 0;
    for(i = 0; i<5; i++)
    {

the control reaches upto this line of code

        m = strstr(tracks[i], search_for);     
        if(m)
        {
            printf("Track%i : '%s' \n", i, tracks[i]);
        }
    }
}

strstr() returns 0

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

}
Sudeep
  • 45
  • 6

1 Answers1

2

Please note that fgets includes any trailing newline that was part of the entry. It can be removed like this

search_for [ strcspn(search_for, "\r\n") ] = 0;   // remove trailing newline etc

otherwise you won't find a match.

Note that fflush(stdin); is non-standard. Note too that the scanf given in one of the linked answers stops at the first whitespace, unless you use certain formatting to prevent it.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • This program is working now. But I would like to know why I shouldn't use `fflush(stdin)`? – Sudeep Jun 18 '16 at 07:55
  • `fflush(stdin);` is not part of the standard C implementation, but it is defined in MSVC and perhaps other implementations. So it is not portable. – Weather Vane Jun 18 '16 at 08:07
  • I have posted a new question. When I researched I found that using `fflush(stdin)` will help me out. Should I use it or search for an alternate solution? – Sudeep Jun 18 '16 at 08:19
  • Only use it if it is documented by your compiler manual and you are willing to write non-portable code. – Weather Vane Jun 18 '16 at 08:28