How to create a simple contact management system using the C language?

The following is an example code of a simple contact management system implemented using the C language.

#include <stdio.h>
#include <string.h>

#define MAX_CONTACTS 100
#define MAX_NAME_LENGTH 50
#define MAX_PHONE_LENGTH 20

struct Contact {
    char name[MAX_NAME_LENGTH];
    char phone[MAX_PHONE_LENGTH];
};

struct Contact contacts[MAX_CONTACTS];
int numContacts = 0;

void addContact() {
    if (numContacts >= MAX_CONTACTS) {
        printf("通讯录已满,无法添加新联系人\n");
        return;
    }

    printf("请输入联系人姓名: ");
    scanf("%s", contacts[numContacts].name);
    printf("请输入联系人电话号码: ");
    scanf("%s", contacts[numContacts].phone);

    numContacts++;
    printf("联系人已添加\n");
}

void displayContacts() {
    printf("通讯录中的联系人:\n");
    for (int i = 0; i < numContacts; i++) {
        printf("%s\t%s\n", contacts[i].name, contacts[i].phone);
    }
}

int main() {
    int choice;

    while (1) {
        printf("\n通讯录管理系统\n");
        printf("1. 添加联系人\n");
        printf("2. 显示所有联系人\n");
        printf("3. 退出\n");
        printf("请选择操作: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                addContact();
                break;
            case 2:
                displayContacts();
                break;
            case 3:
                printf("退出通讯录管理系统\n");
                return 0;
            default:
                printf("无效的操作\n");
        }
    }

    return 0;
}

This simple address book management system includes two functions: adding contacts and displaying all contacts. Users can choose the corresponding operation to add contacts and view all contacts in the address book. Contact information is stored in an array of structures, with each contact containing fields for name and phone number. Different operations are selected through a looping menu, and users can choose to exit the system to end the program.

广告
Closing in 10 seconds
bannerAds