简体   繁体   中英

Print the main string that has the substring inside using strstr() function in C

I'm reading the book "Head First C", and in the chapter 2.5 page 94, the author shows this code:

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]);
     }
 }

This will search the input of the user in the following array of arrays:

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"
};

main() function:

int main()
{
    char search_for[80];
    puts("Search for: ");
    fgets(search_for, 80, stdin);
    find_track(search_for);

    return 0;
}

Output example:

Search for: Iwo
Result:
Track 4: 'The girl from Iwo Jima'

The problem with this code is that the author says that it works, but it doesn't.

The man page of strstr() says that this function will return a null pointer if the sub-string is not encountered in any strings of the array, and it will return a pointer of the sub-string to the beginning, so I did this adaptation to the code:

void find_track(char search_for[]) {
    register int i;
    char *temp;

    for (i = 4; i >= 0; --i) {
        temp = strstr(tracks[i], search_for);
        if (temp) {
            strcpy(temp, tracks[i]);
            printf("Track %i: '%s'\n", i, temp);
        } else {
            puts("Song was not found ... ");
            break;
        }
    }
}

What is wrong with the code? I did a bit of debugging, but everything seems to be fine, so maybe its a logic error, but with something as simple as the strstr() function, something like a logic mistake sounds hard to believe.

Thanks,

And as an extra secondary question... Is this a good book for a noob?

fgets also reads newline character. You need to skip the new line character from the string before passing it to function. May be the below line will help:

search_for[strcspn(search_for, "\n")]='\0';

strcspn gives no. of characters of first parameter before it finds first occurrence of 2nd parameter in 1st parameter. We are setting character at position of '\n' to '\0' which terminates the string at that position so characters after that position will be skipped.

Regards, Haridas.

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