C语言通讯录源代码
时间: 2023-06-22 15:28:29 浏览: 108
以下是一个简单的C语言通讯录源代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CONTACTS 100
struct contact {
char name[50];
char phone[15];
};
struct contact contacts[MAX_CONTACTS];
int num_contacts = 0;
void add_contact() {
if (num_contacts >= MAX_CONTACTS) {
printf("Sorry, the address book is full.\n");
return;
}
struct contact new_contact;
printf("Enter name: ");
fgets(new_contact.name, 50, stdin);
new_contact.name[strcspn(new_contact.name, "\n")] = '\0'; // remove newline character
printf("Enter phone number: ");
fgets(new_contact.phone, 15, stdin);
new_contact.phone[strcspn(new_contact.phone, "\n")] = '\0'; // remove newline character
contacts[num_contacts++] = new_contact;
printf("New contact added.\n");
}
void list_contacts() {
printf("Contact list:\n");
for (int i = 0; i < num_contacts; i++) {
printf("%s: %s\n", contacts[i].name, contacts[i].phone);
}
}
void search_contacts() {
char search_term[50];
printf("Enter search term: ");
fgets(search_term, 50, stdin);
search_term[strcspn(search_term, "\n")] = '\0'; // remove newline character
printf("Search results:\n");
for (int i = 0; i < num_contacts; i++) {
if (strstr(contacts[i].name, search_term) != NULL) {
printf("%s: %s\n", contacts[i].name, contacts[i].phone);
}
}
}
int main() {
char input[10];
while (1) {
printf("Enter command (add, list, search, or quit): ");
fgets(input, 10, stdin);
input[strcspn(input, "\n")] = '\0'; // remove newline character
if (strcmp(input, "add") == 0) {
add_contact();
} else if (strcmp(input, "list") == 0) {
list_contacts();
} else if (strcmp(input, "search") == 0) {
search_contacts();
} else if (strcmp(input, "quit") == 0) {
printf("Goodbye!\n");
return 0;
} else {
printf("Invalid command.\n");
}
}
}
```
这个程序使用结构体来存储联系人的姓名和电话号码,并提供了添加、列出、搜索和退出功能。请注意,此代码示例可能并不完美,仅供参考。
阅读全文