用C写一个查重号码的通讯录代码
时间: 2024-05-05 11:20:20 浏览: 24
好的,以下是一个简单的查重号码的通讯录代码的示例,使用C语言编写:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ENTRIES 1000
typedef struct {
char name[50];
char phone[20];
} Entry;
int find_entry(Entry book[], int size, char *name, char *phone) {
for (int i = 0; i < size; i++) {
if (strcmp(book[i].name, name) == 0) {
// name matches, check phone number
if (strcmp(book[i].phone, phone) == 0) {
// phone number matches, found entry
return i;
} else {
// phone number doesn't match
return -1;
}
}
}
// no match found
return -1;
}
int add_entry(Entry book[], int size, char *name, char *phone) {
if (size >= MAX_ENTRIES) {
// book is full, can't add new entry
return -1;
}
int idx = find_entry(book, size, name, phone);
if (idx >= 0) {
// entry already exists, don't add it again
return -1;
}
// add new entry to end of book
strcpy(book[size].name, name);
strcpy(book[size].phone, phone);
return size + 1;
}
void print_book(Entry book[], int size) {
printf("Name\t\tPhone\n");
printf("------------------------\n");
for (int i = 0; i < size; i++) {
printf("%-15s\t%s\n", book[i].name, book[i].phone);
}
}
int main() {
Entry phone_book[MAX_ENTRIES];
int size = 0;
char name[50];
char phone[20];
printf("Type 'quit' to exit.\n");
while (1) {
printf("Enter name: ");
scanf("%s", name);
if (strcmp(name, "quit") == 0) {
break;
}
printf("Enter phone: ");
scanf("%s", phone);
if (find_entry(phone_book, size, name, phone) >= 0) {
printf("Entry already exists.\n");
} else if (add_entry(phone_book, size, name, phone) < 0) {
printf("Can't add new entry.\n");
} else {
printf("Added new entry.\n");
size++;
}
}
print_book(phone_book, size);
return 0;
}
```
这个程序提供了以下功能:
- 用户可以添加新的通讯录条目,包括姓名和电话号码。
- 当用户添加新条目时,程序会检查通讯录中是否已经存在相同的姓名和电话号码,如果有则不会重复添加。
- 用户可以在任何时候退出程序,并输出当前所有条目。
希望这个示例能够帮助到你!
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)