简体   繁体   中英

Head First C Program ( text search program)

I have a question regarding the below program from Head First C. In the book under main function the writer did not used search_for[strlen(search_for) - 1] = '\\0'; ; still his program ran fine. However when I used original version of the program (as per book),it was not able to find the text which I input. I got the below version from github(which can find text in string) but I still can't understand why it was used . If somebody can explain me I will really appreciate.

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

char tracks[][80] = {
    "I left my heart in Harvad Med School",
    "Newark, Newark -  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);
    search_for[strlen(search_for) - 1] = '\0';
    find_track(search_for);
    return 0;
}

According to cplusplus website, this line:

fgets(search_for, 80, stdin);

Is capturing the newline character, in the end of search_for.

If you type:

heart<intro>

You will get also the character representing the intro keystroke, and you won't find heart\\n in the text.

So doing:

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

will erase the newline from the string ( heart\\n to heart ), because if you do not strip the newline the search will fail.

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

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.

http://www.cplusplus.com/reference/cstdio/fgets/

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

'\\0' is the explicit NULL terminator for string. A null-terminated string is a character string stored as an array containing the characters and terminated with a null character ('\\0', called NUL in ASCII).

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