c编写用于字符串的搜索文件

因此,我必须编写一个从文件中读取并扫描它的函数,以查看其中的任何标题是否与用户放入的标题匹配,并以标题格式打印所有现有标题:(标题)作者:(姓氏,名字)。 如果没有标题匹配则打印出没有找到的标题。 我可以让程序将标题读入数组并以我想要的格式打印,但我的问题是搜索文件以找到匹配的标题来打印它们。程序只是打印出来没有标题匹配5次甚至当有比赛时…非常感谢任何帮助……谢谢……

void findBookByTitle(FILE* fp, char title[]) { FILE* open = fp; char title2[200]; char last[200]; char first[200]; int i=0; while(!feof(fp)) { fscanf(fp, "%[^;];%[^;];%[^\n]", title2, last, first); if( strcmp(title2,title)==0) { printf("Title: %s\n", title2); printf("Author: %s,%s\n", last,first); } else { printf("No books match the title: %s\n", title); } } } 

文本文件说:

 Making The Right Choices; Henry; Mark Time For Change; Robinson; Chris Battle For Air; Jetson; Lola The Right Moves; Henry;Mark People Today; Robinson; Chris 

因此,如果用户想要搜索书籍时间进行更改,则会打印出作者:更改时间作者:亨利,马克但我的function只是打印出来,没有书籍一遍又一遍地匹配……

问题是你的else子句的位置。

如果您修复此间距:

 while(!feof(fp)) { fscanf(fp, "%[^;];%[^;];%[^\n]", title2, last, first); if( strcmp(title2,title)==0) { printf("Title: %s\n", title2); printf("Author: %s,%s\n", last,first); } else { printf("No books match the title: %s\n", title); } } 

您可以看到,如果找不到匹配的EACH标题,则执行以下操作:

  else { printf("No books match the title: %s\n", title); } 

您需要做的是添加一个变量,看看您是否找到了任何东西,并在阅读完所有内容后进行检查

 int found = 0; ... while(!feof(fp)) { fscanf(fp, "%[^;];%[^;];%[^\n]", title2, last, first); if( strcmp(title2,title)==0) { printf("Title: %s\n", title2); printf("Author: %s,%s\n", last,first); found = 1; } } if(!found) { printf("No books match the title: %s\n", title); } .... 

编辑:

来自另一个问题这将向您展示如何使用fscanf省略字符。 基于答案,我认为:

 fscanf(fp, "%200[^;]%*c %200[^;]%*C %200[^\n]%*c", title2, last, first); 

应该做你需要的(用200来防止缓冲区溢出)。

如果你只匹配Making The Right Changes ,那么你的代码就可以了,因为你的fscanf系列正在做你没想到的事情。

这样做是为了将文件的每一行读入单独的字段。

 fscanf(fp, "%[^;];%[^;];%[^\n]", title2, last, first); 

最后的[^\n]告诉fscanf忽略换行符,但它仍然保留在缓冲区中,所以它实际上会读入它读入的下一行。这意味着每本书的标题都有一个\n字符前置到了开头。

我改成了这个:

 fscanf(fp, "%[^;];%[^;];%s\n", title2, last, first); 

这意味着它只会读取该行并按预期将其分解(并将换行符放在地板上)。

这是我基于你编写的示例程序,具有简单的主要function。

 #include  void findBookByTitle(FILE* fp, char title[]) { FILE* open = fp; char title2[200]; char last[200]; char first[200]; int i=0; while(!feof(fp)) { fscanf(fp, "%[^;];%[^;];%s\n", title2, last, first); if( strcmp(title2,title)==0) { printf("I found a match\n"); printf("Title: %s\n", title2); printf("Author: %s,%s\n", last,first); printf("---\n"); return; } } } int main(int argc, char **argv) { char *fname = argv[1]; FILE* fp = fopen(fname, "r"); findBookByTitle(fp, "Making The Right Choices"); findBookByTitle(fp, "Time For Change"); findBookByTitle(fp, "The Right Moves"); fclose(fp); return 0; } 

运行此代码,我得到正确的输出:

 λ > ./a.out sample.txt I found a match Title: Making The Right Choices Author: Henry,Mark --- I found a match Title: Time For Change Author: Robinson,Chris --- I found a match Title: The Right Moves Author: Henry,Mark ---