Weird result of strstr().

Hello,

I am studying C with the book "Head First C". There was a code snippet on the book:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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;
}


The result on the book was:

>Search for: town
>Track 1: 'Newark, Newark - a wonderful town'
>

But on my machine, the result was nothing.

The book shows that the author compiled the demo code with gcc compiler. But I compiled and ran the code with Visual Studio .NET 2003 on Windows XP SP3.

What is the problem? Thanks in advance.

Best regards,

Xiaoguang
fgets adds a newline character to search_for. Get rid of it by adding
search_for[strlen(search_for) - 1] = 0; right after calling fgets.
Many thanks for the reply. That's works. Thanks.
Topic archived. No new replies allowed.