Reputation: 642
here is the struct
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 ;
say i fill this out with x amount of data.
what is a simple way to search the array index of this struct based on one its members, and then print that "Customers" info. Specifically I am looking to search for customers by state.
Upvotes: 0
Views: 2943
Reputation: 1215
Below is an example that I believe will be of some help. Of course, the Customer definition, record printing, and data population need to be expanded. Also note that customer[] is on the stack in this example, so its members aren't zeroed and hence should be set to intended values one way or another.
#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;
}
Upvotes: 2