I have this code here to search a string in a file and display it. How can I edit this piece of code to make it possible to search just a part of this string? say, the file contains the author "dennis zill", if I search "zill" I want the code to display "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
CodePudding user response:
The problem is the line:
if(strcmp(in_name, info[i].bauthor) == 0){
It will succeed only on a full match.
Rather that using strcmp
use strstr
(or its case-insensitive variant strcasestr()
if it's available).
char *strstr(const char *haystack, const char *needle);
The haystack
is the full authors name, needle
the user's input.
Function returns NULL
on failure so it's enough to check if non-NULL was returned.
if(strstr(info[i].bauthor, in_name) != NULL){