利用结构体实现手机里的“联系人”的功能,要求能存储并能通过姓名或电话查找某个人的详细信息。
时间: 2024-05-04 15:18:36 浏览: 16
可以通过定义一个包含姓名、电话和其他相关详细信息的结构体来实现手机里的“联系人”的功能。例如:
```c
#include <stdio.h>
#include <string.h>
#define MAX_CONTACTS 100
struct Contact {
char name[50];
char phone[20];
char email[50];
char address[100];
};
struct Phonebook {
struct Contact contacts[MAX_CONTACTS];
int numContacts;
};
void addContact(struct Phonebook *pb, const char *name, const char *phone, const char *email, const char *address) {
if (pb->numContacts >= MAX_CONTACTS) {
printf("Phonebook is full\n");
return;
}
struct Contact *contact = &pb->contacts[pb->numContacts++];
strcpy(contact->name, name);
strcpy(contact->phone, phone);
strcpy(contact->email, email);
strcpy(contact->address, address);
printf("Contact added successfully\n");
}
void searchContact(struct Phonebook *pb, const char *query) {
int found = 0;
for (int i = 0; i < pb->numContacts; i++) {
struct Contact *contact = &pb->contacts[i];
if (strstr(contact->name, query) || strstr(contact->phone, query)) {
printf("Name: %s\nPhone: %s\nEmail: %s\nAddress: %s\n", contact->name, contact->phone, contact->email, contact->address);
found = 1;
}
}
if (!found) {
printf("No matching contacts found\n");
}
}
int main() {
struct Phonebook pb = {0};
addContact(&pb, "Alice", "1234567890", "alice@example.com", "123 Main St");
addContact(&pb, "Bob", "2345678901", "bob@example.com", "456 Main St");
addContact(&pb, "Charlie", "3456789012", "charlie@example.com", "789 Main St");
searchContact(&pb, "Bob");
searchContact(&pb, "Main");
return 0;
}
```
在上面的例子中,我们定义了一个 `Contact` 结构体来存储每个联系人的详细信息,另外定义了一个 `Phonebook` 结构体来存储所有联系人。我们可以通过调用 `addContact` 函数来添加联系人,并且可以通过调用 `searchContact` 函数来查找所有包含某个查询字符串的联系人。注意,在上面的例子中,我们使用了 `strstr` 函数来在姓名和电话号码中查找查询字符串。