以下程序应搜索多维数组。当我输入单词town
作为输入时,它应该返回Track 1: Newark,Newark-A Wonderful Town
但我没有收到任何输出(没有任何反应),任何想法如何解决它?
我正在研究Head First C的书。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Run this program using the console pauser
or add your own _getch, system("pause") or input loop */
char tracks[][80]={
"I Left My Heart In Harvard Med School",
"Newark,Newark-A Wonderful Town",
"From Here to Maternity",
"The Girl From Iwo Jima",
};
void find_track(char search_for[]){
int i;
for (i=0;i<=4;i++){
if(strstr(tracks[i],search_for)){
printf("Track %i:'%s' \n",i,tracks[i]);
}
}
}
int main(int argc, char *argv[]) {
char search_for[80];
printf("Search for: ");
fgets(search_for,80,stdin);
find_track(search_for);
return 0;
}
如上所述,fgets
会根据您的输入存储换行符,但不会匹配。只要你匹配标题中测试的情况,从search_for
字符串中删除最后一个字符将使其工作。另外,请注意你的for
循环应该有i < 4
而不是i <= 4
。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char tracks[][80]={
"I Left My Heart In Harvard Med School",
"Newark,Newark-A Wonderful Town",
"From Here to Maternity",
"The Girl From Iwo Jima",
};
void find_track(char search_for[]){
int i;
for (i=0;i<4;i++){
if(strstr(tracks[i], search_for)){
printf("Track %i:'%s' \n",i,tracks[i]);
}
}
}
int main(int argc, char *argv[]) {
char search_for[80];
printf("Search for: ");
fgets(search_for,80,stdin);
search_for[strlen(search_for)-1] = '\0'; // truncate input
find_track(search_for);
return 0;
}