Search code examples
clistinputlinked-liststrncmp

C Strncmp Return Partial Input


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!


Solution

  • 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) {