4

This program is not giving any output... the function find_track should return the track if a matching string is entered to it.

#include<stdio.h>
#include<string.h>

char tracks[][80] = {
    "I left my heart in Harward 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 search_for[80];
    printf("Search for : ");
    fgets(search_for,80,stdin);
    find_track(search_for);
    return 0;
}
Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
  • I'm sorry to see that this question was closed as too localized because it was the exact same problem I just hit and the first answer nailed it. – Ovid Feb 08 '13 at 20:09

1 Answers1

5

fgets() reads the line you enter, as the docs says, this includes any newline that you input to your program. So of you type "with" and hit enter, you program will get the string "with\n".

So get rid of that newline:

if (fgets(search_for,80,stdin)  && search_for[0]) [
    search_for[strlen(search_for) - 1] = 0;
    find_track(search_for);
}
nos
  • 223,662
  • 58
  • 417
  • 506
  • The code in the question is given in "Head First c" ... and i have used scanf instead of fgets ..... Thanks for the answer :)) –  Feb 02 '13 at 16:11
  • Suppose fgets gets to the 79th character and finds that it isn't a '\n'. What happens to that character? It gets discarded by this line of code: `search_for[strlen(search_for) - 1] = 0;`. A well designed program should never discard input. Consider `search_for[strcspn(search_for, "\n")] = '\0';`, instead. – autistic Feb 02 '13 at 16:12