#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RECORDS 10
下面的功能是我需要帮助的。
static char searchforRecordbystate(char input[3])
{
for/while/if循环
搜索结构数组成员
如果找到匹配项
返回(打印)找到匹配项的整个结构
return 0;
}
主要功能-有史以来第一次使用指针(xcode不是抱怨它设置得尽可能严格),但欢迎大家抱怨,特别是如果我做了一个巨大的监督。
int main() {
typedef struct {
char *firstName[RECORDS];
char *lastName[RECORDS];
char *street[RECORDS];
char *city[RECORDS];
char *state[RECORDS];
int *zip[RECORDS];
char *phone[RECORDS];
int *accountId[RECORDS];
} Customer ;
typedef int records;
records i = 0;
数据输入的数组循环
Customer custArray[RECORDS];
printf("================================================================\n");
for(i = 0; i < RECORDS; ++i)
{
printf("Enter data for customer %d\n", i + 1);
printf("Enter firstname, last name, phone\n");
scanf("%s %s %s", *custArray[i].firstName, *custArray[i].lastName, *custArray[i].phone);
printf("Enter Address (Street City State ZIP)");
scanf("%s %s %s*c %d", *custArray[i].street, *custArray[i].city, *custArray[i].state, *custArray[i].zip);
break;
}
char input[3];
printf("Enter in state to search for customer a customer record:\n");
scanf("%s", input);
searchforRecordbystate(input);
}
没有错误检查的必要,只是试图爬到学习c的时刻。而且该成员国不会有重复的数据希望这能让事情变得容易些。
最佳答案
如何编写搜索函数以在结构中查找匹配项
数组并返回(printf)它匹配的整个结构?
在函数外部声明struct数据类型,使其对整个模块“可见”。
创建一个能够漂亮地打印结构的函数:void CustomerPrint(const Customer *toPrint) { ...}
创建一个搜索函数,该函数遍历数组,比较给定的参数:Customer *CustomerFind(const char *name) {...}
通过调用CustomerFind
连接两个功能块,如果结果不是NULL
调用CustomerPrint
函数。
当然,这些接口只是建议,可能会被更改。如果你对提案的细节有任何疑问,请留下评论,如果你愿意的话,我会详细解释的。
额外的想法
当我重读我的文章时,我意识到我在上述建议中所做的一些决定无论如何都需要一个解释:
在CustomerPrint中,指针是const?因为这个函数不会修改结构的任何字段。因此我们告诉编译器我们不会改变任何东西。
CustomerFind应具有所有可搜索字段的参数。(因此鼓励您扩展签名)我建议通过指针获取所有“比较”值,并让调用者使用与搜索无关的指针NULL
。(例如,如果您有name
和city
,您可以将city
保留为空,以便只搜索第一次出现的name
。
函数本身在记录数组中运行,并比较不NULL
的字段。如果找到一个,则返回指向该元素的指针(return &(myRecords[n]);
)。如果函数到达数组的末尾,它将返回NULL
以指示没有匹配的记录。
如果你想拥有“搜索-搜索下一步”功能,也可以引入一个概念。如果你也对这个概念感兴趣,请告诉我。