【发布时间】:2018-03-20 16:20:37
【问题描述】:
file.txt 上的数据如图所示放置。
我的代码是这样的:
int searchBookname()
{
FILE *myFile=fopen("file.txt","r+");
if (myFile!=NULL) // file exists
{
char tmp1[512];
char tmp2[512];
while(fgets(tmp1,512,myFile)!=EOF)
{
puts("Insert the Book Name: ");
scanf("%s",tmp2);
if(strstr(tmp1,tmp2)!=NULL){
printf("the book is found: %s\n\n",tmp1);
}else{
puts("\nSorry there was no Match with this name! Maybe Book is not recorded yet :(\n");
}
}
}else{ // file doesn't exist
puts("\nDatabase is not created yet. Please record a new book to create a simple database\n");
exit(0);
}
fclose(myFile); // closing the file
}
由于某种原因,它不断跳过 if 语句 2 次 第三次打印正确的结果。 无论我尝试搜索什么书,都会发生这种情况。 见here
如何让它在不跳过 if 语句的情况下找到结果。
【问题讨论】:
-
你逐行读取文件。因此,在第三个循环/行中,有一条带有“book1”的记录。代码工作正常。也许您想在 while 循环之外向用户询问书名,并在每一行中搜索给定的书名。如果有,您可以打印您的消息并从循环中中断。
-
我尝试了您的代码,但无法从该图像中读取。投票关闭为“不可在本地重现”。 (即使我创建了一个虚拟 file.txt,它似乎也不会生成图像,因此该部分也无法重现。)
-
欢迎来到 Stack Overflow!您的代码不完整;特别是,它似乎缺少一个
main()函数和至少一个#include。请edit您的代码,这是您问题的minimal reproducible example(包括任何必要的输入,但最好不需要任何输入),然后我们可以尝试重现并解决它。您还应该阅读How to Ask。