Question

can't seem to see my error here, when I compile and run I just get the "Search for: " coming up, I enter something that should show a result but nothing happens and just exits.

I've recreated this code exactly(from what I can see!) from the Head First C book but it's not working the same, theirs appears to show the results when you search for it.

So hit me up guys, what have I done wrong? Thanks in advance!!

Btw, arrays + array pointers do my head in lol.

Here's the code:

#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;
    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;
}
Was it helpful?

Solution

The fgets function, as stated here, includes the new line (\n) character, since it is considered a valid character:

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

This means that you are going to check, for example:

"I left my heart in Harvard Med School"

with

"I left\n"

so the match doesn't occur. You could try using gets or replacing the \n character with a NUL (\0):

char search_for[80];
fgets(search_for, 80, stdin);
search_for[strlen(search_for)-1] = '\0';

OTHER TIPS

In fgets man page: "Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer."

So in you code, after the final "Enter" is pressed, the value stored in search_for is actually "what_you_type"+"\n". But tracks does not contain any "\n", it's not surprise of not finding what you have typed in it.

Change tracks to:

 char tracks[][80] = 
 {
    "I left my heart in Harvard Med School\n",
    "Newark, Newark - A wonderful town\n",
    "Dancing with a Dork\n",
    "From here to maternity\n",
    "The girl from Iwo Jima\n",
};

and type the whole sentence or something like "Iwo Jima", you will definitely find what you are looking for.

Jack's answer is OK.

You can replace

fgets(search_for, 80, stdin);

by

scanf("%79s", search_for);

This is a erratum of the book. You can view the others at Errata for Head First C.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top