首页 > 解决方案 > 在链表中搜索字符串 C

问题描述

我在 C 中搜索链表时遇到问题。我设法搜索并找到一个整数条目,但字符串(名字和姓氏)有问题。基本上,有三个功能可以按名字、姓氏和号码在电话簿中搜索条目。是否也可以在找到搜索时显示该条目?请在下面找到代码。谢谢你的帮助。

struct node { 
    char firstname[32]; 
    char lastname[32]; 
    int *number; 
    struct node *next; 
}*head; 

struct node *start=NULL; 

struct node *getnode() { 
    return((struct node *)malloc(sizeof(struct node)));
}

void insert() { 
    struct node *temp,*nn; 
    nn=getnode(); 
    temp=start; 
    while(temp->next!=NULL) 
    { 
        temp=temp->next; 
    } 
    printf("Enter First name:\n"); 
    scanf("%s",&nn->firstname); 
    printf("Enter Last name:\n"); 
    scanf("%s",&nn->lastname); 
    printf("Enter number:\n"); 
    scanf("%d",&nn->number); 
    temp->next=nn; 
    nn->next=NULL; 
    display(start);
} 


struct node *create() {
    struct node *temp,*nn; 
    if(start!=NULL) insert(); 
    else { 
        nn=getnode(); 
        start=nn; 
        temp=start; 
        printf("Enter First name:\n"); 
        scanf("%s",&nn->firstname); 
        printf("Enter Last name:\n"); 
        scanf("%s",&nn->lastname); 
        printf("Enter number:\n"); 
        scanf("%d",&nn->number); 
        nn->next=NULL;
    }
} 

void searchByFirstName() { 
    char *f;
    struct node* temp, *nn;
    temp = start;
    while (temp != NULL){
        printf("Enter First Name to be searched:\n");  scanf("%s",&f);
        printf("%s", &f);
        if (temp -> firstname == f){
            printf ("\n Record Found!\n");
            temp = temp -> next;
        }else{
            printf ("\n Record not found\n");
        } 
    }
} 

void searchByLastName() { 
    char *f;
    struct node* temp, *nn;
    temp = start;
    if (temp != NULL){
        printf("Enter Last Name to be searched:\n");  scanf("%s",&f);
        printf("%s", &f);
        if (temp -> lastname == f){
            printf ("\n Record Found!\n");
            temp = temp -> next;
        }else{
            printf ("\n Record not found\n");
        } 
    }
}

void searchByNumber() { 
    int *l;
    struct node* temp, *nn;
    temp = start;
    if (temp != NULL){
        printf("Enter Number to be searched:\n");  scanf("%d",&l);
        if (temp -> number == l){
            printf ("\n Record Found!\n");
            temp = temp -> next;
        }else{
            printf ("\n Record not found\n");
        } 
    }
}

标签: cstringsearchlinked-list

解决方案


在 C 中,您不能只使用运算符 == 比较两个字符串(也称为 char *)。在 C 中处理字符串时,可以使用标准函数 (#include <string.h>),例如:

strcmp(temp->lastname, f) // returns 0 in case of a perfect match

推荐阅读