Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

pointers - C Code for String matching[Head First C] doesn't seem to work

#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'
", i, tracks[i]);
    }

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

}

This is the code taken directly from Head First C. This doesn't work.On the other hand if I change the line in main

char search_for[80];

to

char *search_for = "town"

It gives me the expected result. I don't understand why it doesn't work.I understand that directly pasting the code and telling you to find errors is not very much acceptable here but i guess it is a very small piece of basic code so it will do.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem with the code above is that it doesn't account for the fact that fgets leaves the newline in the string. So when you type town and hit enter, you'll end up searching for "town ".

A cheap way to solve this would be to fix the string after calling fgets

search_for[strlen(search_for) - 1] = 0;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...