gpt4 book ai didi

c - 自动点唱机代码中的错误(首先是C)

转载 作者:行者123 更新时间:2023-12-02 07:31:24 25 4
gpt4 key购买 nike

我正在用Head First C书学习C编程。
因此,我正在尝试编译可在第94页找到的代码:

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

char tracks[][80] = {
"I left my heart in Harvard Mead 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(void)
{
char search_for[80];

printf("Search for: ");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}

查看以下输出:
-----------------------------------------------------------------./jukebox                                                      --Search for: town                                               --kawaban9a-14H:~/Code/C/Head_C/Chapter_3$ (so, nothing happens) -------------------------------------------------------------------

It's ok, no compiler complaint, but when I run it, there's no result.I read this code several times and I can't understand why, where's the bug?If someone could help me with this, I'll be grateful.

SOME MINUTES LATER ...

Thank you friend cnicutar for your answer that helped me figure out the problem with '\n'.I solved this problem by just inserting a piece of code before the call to the find_track() function.

Check it out:

int main(void)
{
char search_for[80];

printf("Search for: ");
fgets(search_for, 80, stdin);

size_t ln = strlen(search_for) - 1;
if (search_for[ln] == '\n')
search_for[ln] = '\0';

find_track(search_for);
return 0;
}

最佳答案

问题在于fgets将换行符存储在目标字符串中。因此,您的strstr需要找到"town\n"。一种解决方案是在search_for之后修剪fgets以摆脱换行符。

关于c - 自动点唱机代码中的错误(首先是C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21318269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com