C 程序在曲目数组中搜索曲目

C program to search for a track in an array of tracks

我有一个程序,它应该根据文本输入输出曲目名称和编号(例如输入 'town' 应该输出 "Track 1: 'Newark, Newark - a wonderful town'")但输出当前为空(没有返回任何内容,该程序只是停止执行而没有任何错误)。这是程序:

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

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

请帮忙:)

fgets(search_for, 80, stdin);

捕获 \n 换行符尾随按下 Return 的正确字符串输入并将其写入 search_for.


删除它的最佳方法在 this answer to Removing trailing newline character from fgets() input 中有最好的解释。

通过

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

在调用

之前
find_track(search_for);

删除或更好地说用 [=18=] 替换它。


整个代码应该是:

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

int main()
{
    char search_for[80];
    printf("Search for: ");
    fgets(search_for, 80, stdin);
    search_for[strcspn(search_for, "\n")] = 0;    // here is the change.
    find_track(search_for);
    return 0;
}