如何将结构字段与C中的变量进行比较? [复制]
Posted
技术标签:
【中文标题】如何将结构字段与C中的变量进行比较? [复制]【英文标题】:How to compare struct fields to variables in C? [duplicate] 【发布时间】:2022-01-09 03:42:54 【问题描述】:这是链表程序中删除功能的一部分。我正在尝试将当前结构节点的字段与用户读取的用于搜索的字段进行比较。我知道我的节点引用有效,因为我可以自己打印出当前字段,但我在 if 语句中与变量的比较没有。如何将当前字段与用户数据进行比较?谢谢
int deleteEmployee(void)
char name[MAX_NAME_LENGTH];
char gender[2];
int age;
char position[MAX_JOB_LENGTH];
int placeInList = 0;
Employee *current = employeeListHead;
Employee *previous = employeeListHead;
printf("Enter details of employee to delete: \n");
printf("Name: \n");
scanf(" %100[^\n]s", name);
scanf("%*[^\n]%*c");
printf("Gender: \n");
scanf(" %1s", gender);
scanf("%*[^\n]%*c");
printf("Age: \n");
scanf(" %d", &age);
scanf("%*[^\n]%*c");
printf("Title: \n");
scanf(" %100[^\n]s", position);
scanf("%*[^\n]%*c");
//while elements in list to search
while(current != NULL)
这个具体
//handling a match on each iteration
if (current->name == name && current->gender == gender && current->age == age && current->position == position)
printf("\nIs this the emplyee you'd like to delete? Please confirm (Y/N) %s %s %d %s \n\n", name, gender, age, position);
char choice;
scanf(" %c", &choice);
//if delete is confirmed
if (choice == 'Y' || choice == 'y')
//if head of list
if(current == employeeListHead)
employeeListHead = current->next;
current = NULL;
return EXIT_SUCCESS;
//if tail
else if(current->next == NULL)
//change previous nodes pointer
for (int i=0; current!=NULL && i < placeInList-1; i++)
previous->next = NULL;
current = NULL;
return EXIT_SUCCESS;
//if inside list
else
for (int i=0; current!=NULL && i < placeInList-1; i++)
previous->next = current->next;
current = NULL;
return EXIT_SUCCESS;
//end if yes selected to delete
//if delete is confirmed
if (choice == 'N' || choice == 'n')
printf("You selected N. Returning to main menu.");
EXIT_FAILURE;
//end if no selected to delete
//end if a match
//iterate to next set of nodes
current = current->next;
previous = previous->next;
placeInList++;
//end iterating through list
printf("Employee not found in system.\n");
return EXIT_FAILURE;
【问题讨论】:
使用strcmp
比较C中的字符串,而不是==
【参考方案1】:
您需要使用strcmp
来比较字符串。当您编写current->name == name
时,您的程序只是比较两个指针的位置。 (但是你没有给出name
的定义,所以很难确定。)
尝试将所有字符串比较替换为:
0 == strcmp(current->name, name)
【讨论】:
以上是关于如何将结构字段与C中的变量进行比较? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
如何将 SqlDbtype.Money = 0 与 Sql 服务器中的货币字段进行比较