这是结构
int main() {
typedef struct {
char firstName[25];
char lastName[30];
char street[35];
char city[20];
char state[3];
int zip;
char phone[15];
int accountId;
}Customer ;
假设我填写了 x 数量的数据。
有一种简单的方法可以根据该结构的一个成员搜索该结构的数组索引,然后打印“客户”信息。具体来说,我希望按州搜索客户。
最佳答案
下面是一个例子,我相信会对您有所帮助。当然,客户定义、记录打印和数据填充都需要扩展。另请注意,在此示例中,customer[] 位于堆栈上,因此其成员不会归零,因此应以某种方式设置为预期值。
#include <string.h>
#include <stdio.h>
#define NUM_RECORDS 10
int main()
{
int i;
typedef struct {
char state[3];
} Customer;
Customer customer[NUM_RECORDS];
strcpy(customer[2].state, "CA");
for (i = 0; i < NUM_RECORDS; i++)
{
// if this customer record's state member is "CA"
if (!strcmp(customer[i].state, "CA"))
printf("state %d: %s\n", i, customer[i].state);
}
// Prints "state 2: CA"
return 0;
}
关于C 结构体数组和搜索 : Attempting to a match a member and prnt the entire struct if a match is found.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15036777/