我正在关注第一本C书,现在我正在遵循弦理论部分。编写了一个程序,当搜索到轨道名称的一部分并找到它时,返回轨道号和轨道的全名。但是代码运行不正常。有人可以告诉我这个C程序有什么问题:
#include <stdio.h>
#include <stdlib.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;i5;i++){
if (strstr(tracks[i], search_for)){
printf("Track %i: '%s'\n", i, tracks[i]);}
}
}
int main()
{
printf("Hello World!\n");
char search_for[80];
printf("Search for: ");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}
答案 0 :(得分:-1)
我发现使用fgets()
是获取用户输入错误的原因,并在strstr()
函数上使用此字符串。
通过问题评论部分中的Blastfurnace,woz和其他人提供一些好的建议,我可以解决这个问题。
#include <stdio.h>
#include <stdlib.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;
char * pch;
int flag = 0;
for(i=0;i<5;i++){
pch = strstr(tracks[i], search_for);
if (pch){
printf("find in Track %i: '%s'\n", i, tracks[i]);
flag = 1;//find
}
}
if (flag == 0)// not found
printf("Track Not found\n");
}
int main()
{
char search_for[80];
printf("Search for: ");
fscanf (stdin, "%s", search_for);
find_track(search_for);
return 0;
}