1

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!

AstroCB
  • 12,337
  • 20
  • 57
  • 73
James Manes
  • 526
  • 1
  • 11
  • 23

3 Answers3

3

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) {
simonc
  • 41,632
  • 12
  • 85
  • 103
  • No no... I want to return a full record with partial match. Sorry if I was not clear in my question. For example I would enter "mag" and then the result it would spit out would be "maggie numberhere addrhere." – James Manes Dec 09 '12 at 22:31
  • @JamesManes Ah, right. My edited answer hopefully covers things for you then – simonc Dec 09 '12 at 22:32
  • Very nice! Again sorry for not being clear. Thank you for the help! – James Manes Dec 09 '12 at 22:35
2

Instead of strncmp(current->name, search, MAX) use strncmp(current->name, search, strlen(search)) or use the strstr function.

ChrisW
  • 54,973
  • 13
  • 116
  • 224
0

strncmp compares the number of characters to compare. So don't compare that many.

Start by comparing the string length, or just use strcmp().

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466