【发布时间】:2021-09-14 10:36:22
【问题描述】:
我在这里有这段代码来搜索文件中的字符串并显示它。我如何编辑这段代码,以便只搜索该字符串的一部分? 比如说,该文件包含作者“dennis zill”,如果我搜索“zill”,我希望代码显示“dennis zill”。
int searchauthor(FILE *ptr) //searching starts
{
int save;
char de;
char in_name[30];
int flag = 1;
save = readbooks();
ptr = fopen("books info.txt", "r");
fflush(stdin);
printf("\n Enter the name of the author: ");
gets(in_name);
printf("-------------------------------------------------");
for(int i = 0; i < save; i++){
if(strcmpi(in_name, info[i].bauthor) == 0){
printf("\n Book name: %s\n Price: %u\n Number of books available: %u\n Number of pages: %u\n-------------------------------------------------", info[i].bname, info[i].price, info[i].numavail, info[i].bpages);
flag = 0;
}
}
if (flag == 1){
printf("\n Not found.\n Do you want to try another search [Y/N]? ");
scanf("%c", &de);
if(de == 'y' || de == 'Y'){
system("cls");
in_name[MAX] = reset(in_name);
fclose(ptr);
return 2;
}
else if(de == 'n' || de == 'N'){
printf("\n You will be redirected to main menu");
for(int k = 1; k <= 5; k++){
Sleep(300);
printf(".");
}
system("cls");
return 1;
}
}
printf("\n\n Do you want to try another search [Y/N]? ");
scanf("%c", &de);
if (de == 'y' || de == 'Y') {
system("cls");
in_name[MAX] = reset(in_name);
return 2; //return 2 to case 3 to search again
}
else if (de == 'n' || de == 'N') {
system("cls");
printf("\n You will be redirected to main menu");
for(int k = 1; k <= 5; k++){
Sleep(300);
printf(".");
}
system("cls");
return 1;
}
} //searching ends
【问题讨论】:
-
尝试使用
strstr()或strcasestr()而不是strcmp() -
请将纯文本添加为文本,而不是屏幕截图。
-
@tstanisl 如果我使用 strstr() 它只会显示文件中的所有内容!!
-
@AliElneklawy,你试过
strstr(info[i].bauthor, in_name) != NULL吗? -
@tstanisl 完成。有用!我可以让它不区分大小写吗?