C 结构体数组和搜索 : Attempting to a match a member and prnt the entire struct if a match is found.

标签 c search struct printf

这是结构

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/

相关文章:

c - 在 C 函数中更改 __stack_chk_guard 是否合法?

c - 归零并初始化 C 结构

arrays - 查找具有给定总和的已排序数组的子集的最有效算法

amazon-web-services - 模板格式错误: [/Resources/ElasticsearchDomain] resource definition is malformed

c++ - 结构消耗太多内存

c - 如何按字母顺序在列表中插入结构体

c - 遍历c中的字符串数组

C 编程 - 将空格分隔的字符串读入 BST

c - Linux RPC 调用很慢

linux - 如何在linux中查找包含字符串的行