我正在尝试搜索轨道数组中是否有任何轨道可用。当我给任何输入时,strstr()
函数返回false。如果我使用else块,则每次执行其他块。
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",
};
// function to search the track with entered search string //
void find_track(char search_for[]) {
int i;
for (i = 0; i < 5; i++) {
/** this if condition is returning false every time */
if (strstr(tracks[i], search_for)){
printf("Track %i: '%s'\n", i, tracks[i]);
}/**else{
printf("some thing went wrong @ %i\n", i);
}**/
}
}
int main() {
char search_for[80];
printf("Search for: ");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}
输入:
gcc test.c -o test && test
搜索:with
预期结果:Track 2:'Dancing with a Dork'
请帮帮我。
答案 0 :(得分:2)
fgets
也会读取换行符。您需要先将其从search_for
中删除,然后再将其传递给find_track
。