Reputation: 526
I currently have a linked list structure running and I need to find a way to let a user search the struct for a certain field. I have this done, but the problem is it must be exact. For example, if the user enters "maggie" it will return the result, but if the user types in "mag" it will not return the maggie record like I want.
int counter = 0;
char search[MAX];
record_type *current = head;
printf("\n\n- - - > Search Records\n\n");
printf("\tSearch: ");
scanf("%s", search);
/* search till end of nodes */
while(current != (record_type*) NULL) {
if(strncmp(current->name, search, MAX) == 0) {
printf("\t%i. %s", counter, current->name);
printf("\t%u", current->telephone);
printf("\t%s\n", current->address);
counter++;
}
current = current->next;
}
Any ideas? I'm guessing there is a way to just compare with chars? Thanks!
Upvotes: 1
Views: 313
Reputation: 56123
Instead of strncmp(current->name, search, MAX)
use strncmp(current->name, search, strlen(search))
or use the strstr
function.
Upvotes: 2
Reputation: 67345
strncmp
compares the number of characters to compare. So don't compare that many.
Start by comparing the string length, or just use strcmp()
.
Upvotes: 0
Reputation: 42205
You're question isn't entirely clear...
If you only want to return exact matches, use strcmp
instead
if (strcmp(current->name, search) == 0) {
If you want to return partial matches, use strncmp
but over a size that matches your search string:
if (strncmp(current->name, search, strlen(search)) == 0) {
Upvotes: 3