简体   繁体   中英

bug in jukebox code (head first C)

I'm studying C programming with Head First C book. So I'm trying to compile this code that we can find at page 94:

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

char tracks[][80] = {
    "I left my heart in Harvard Mead 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(void)
{
    char search_for[80];

    printf("Search for: ");
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0;
}

Look at this output:

-----------------------------------------------------------------
./jukebox                                                      --
Search for: town                                               --
kawaban9a-14H:~/Code/C/Head_C/Chapter_3$ (so, nothing happens) --
-----------------------------------------------------------------

It's ok, no compiler complaint, but when I run it, there's no result. I read this code several times and I can't understand why, where's the bug? If someone could help me with this, I'll be grateful.

SOME MINUTES LATER ...

Thank you friend cnicutar for your answer that helped me figure out the problem with '\\n' . I solved this problem by just inserting a piece of code before the call to the find_track() function.

Check it out:

int main(void)
{
    char search_for[80];

    printf("Search for: ");
    fgets(search_for, 80, stdin);

    size_t ln = strlen(search_for) - 1;
    if (search_for[ln] == '\n')
        search_for[ln] = '\0';

    find_track(search_for);
    return 0;
}

The problem is that fgets stores the newline in the destination string. So your strstr needs to find "town\\n" . One solution would be to trim search_for after fgets to get rid of the newline.

fgets替换为:

scanf("%79s", search_for);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM