c - 在链表中搜索字符串 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");
}
}
}
解决方案
在 C 中,您不能只使用运算符 == 比较两个字符串(也称为 char *)。在 C 中处理字符串时,可以使用标准函数 (#include <string.h>),例如:
strcmp(temp->lastname, f) // returns 0 in case of a perfect match
推荐阅读
- c# - 2 具有相同名称和类的 Windows
- python - 仅在 Keras 中训练多输出模型时显示总损失
- python - 如何将 pandas 数据框转换为 sqlite 数据库
- github - 在 Jekyll 页面的前端自动设置日期
- node.js - 在进行 REST API 调用时,非 ascii 字符(如“æ”)的 NodeJS 编码问题
- javascript - 从 mongodb gridfs 数据库中检索多部分表单数据并在反应本机应用程序中显示图像
- apache-kafka - 如何对 Kafka 中的数据进行反规范化?
- c - 为什么一个字节的大小(以位为单位)实现定义并带有该变量?我认为一个字节始终是 8 位
- python - 哪些损失函数和指标用于具有非常高的负数与正数比率的多标签分类?
- amazon-web-services - AWS CDK python 客户端使用 cdk deploy 出错