0

似乎在这里看不到我的错误,当我编译和运行时,我只是得到“搜索:”,我输入了一些应该显示结果的东西,但什么也没发生,只是退出。

我已经从 Head First C 书中准确地重新创建了这段代码(据我所见!),但它的工作方式不一样,当你搜索它时,它们似乎会显示结果。

所以打我,伙计们,我做错了什么?提前致谢!!

顺便说一句,数组+数组指针让我很头疼。

这是代码:

#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;
}
4

3 回答 3

4

如此处所述,fgets函数包括换行符 ( ) 字符,因为它被视为有效字符:\n

换行符使 fgets 停止读取,但它被函数视为有效字符并包含在复制到 str 的字符串中。

这意味着您要检查,例如:

"I left my heart in Harvard Med School"

"I left\n"

所以匹配不会发生。您可以尝试使用NUL ( )gets或替换该字符:\n\0

char search_for[80];
fgets(search_for, 80, stdin);
search_for[strlen(search_for)-1] = '\0';
于 2013-08-03T13:49:41.757 回答
1

In fgets man page: "Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer."

So in you code, after the final "Enter" is pressed, the value stored in search_for is actually "what_you_type"+"\n". But tracks does not contain any "\n", it's not surprise of not finding what you have typed in it.

Change tracks to:

 char tracks[][80] = 
 {
    "I left my heart in Harvard Med School\n",
    "Newark, Newark - A wonderful town\n",
    "Dancing with a Dork\n",
    "From here to maternity\n",
    "The girl from Iwo Jima\n",
};

and type the whole sentence or something like "Iwo Jima", you will definitely find what you are looking for.

于 2013-08-03T14:11:26.320 回答
1

杰克的回答是好的。

你可以更换

fgets(search_for, 80, 标准输入);

经过

scanf("%79s", search_for);

这是本书的勘误。您可以在勘误表中查看 Head First C的其他内容。

于 2014-01-28T18:29:03.793 回答