简体   繁体   English

Head First C程序(文本搜索程序)

[英]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'; 我对Head First C的以下程序有疑问。在本书的主要功能下,作者没有使用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 . 我从github获得了以下版本(可以在字符串中找到文本),但我仍然不明白为什么使用它。 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: 根据cplusplus网站,此行:

fgets(search_for, 80, stdin);

Is capturing the newline character, in the end of search_for. 在search_for的末尾捕获newline

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. 您还将获得代表intro按键的字符,并且在文本中找不到heart\\n

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. 删除字符串中的换行符( heart\\n to heart ),因为如果不删除换行符,搜索将失败。

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. 从流中读取字符,并将它们作为C字符串存储到str中,直到已读取(num-1)个字符或到达换行符或到达文件末尾为止,以先发生的为准。

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. 换行符使fgets停止读取,但该函数将其视为有效字符并包含在复制到str的字符串中。

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

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

'\\0' is the explicit NULL terminator for string. '\\ 0'是字符串的显式NULL终止符。 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). 以空字符结尾的字符串是存储为包含字符的数组并以空字符('\\ 0',在ASCII中称为NUL)结尾的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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