3

我正在制作一个搜索程序,但它不会输出我输入的句子。它最终什么也没显示。只是第 1 行中的“搜索:”。

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

将 Visual Studio 2010 与 C 结合使用

4

2 回答 2

3
fgets(search_for, 80, stdin); 

如果您heart在按下回车键后输入

fgets() 读入换行符search_for

    Now search_for=="heart\n";

\n在 search_for 结束时删除

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

   find_track(search_for);
于 2013-10-13T09:14:14.920 回答
0

最简单的解决方案是更换:

fgets(search_for, 80, stdin); 

fscanf(stdin, "%s", search_for);

使用这种方法,请注意不要在搜索中输入超过 79 个字符。

于 2013-10-13T09:22:55.803 回答