Address book (c language version)

Posted by aamirshah on Sun, 16 Jan 2022 10:20:02 +0100

preface

When we use mobile phones to make calls, we always use the address book when sending messages. What is the address book for?

Obviously, it is used to store a person's information (name, telephone, address), etc We can query, delete, add and other related information

The blogger wrote this blog to use our recent knowledge of C language to make a simple version of address book

① Clarify the purpose of the project

Having seen the blogger's blog before, the little partner may know the blogger's blog style Before writing any small project, bloggers first sort out the purpose, then build the logical structure, and then realize modularization respectively This time is no exception

Purpose:

  • It can store personal information (name, gender, age, telephone, address) and explain the structure
  • There is no limit to the number of people to store (description requires dynamic memory)
  • There is a reminder menu to prompt relevant commands
  • Commands are (0 exit, 1 add information, 2 delete information, 3 query information, 4 modify information, 5 display all information, 6 sort information)

② Project structure construction

After clarifying the purpose, we can build a logical structure. We know that human information should be stored in a structure And press the relevant command to enter the relevant module, then

There must be do while and switch case

#include <stdio.h>
struct information //Personal information form
{
	char name[20];//full name
	char sex[10]; //Gender
	int age;//Age
	char tele[15];//Telephone
	char address[40];//address
};

struct contact  //mail list
{
	struct information* info; //Because there is no limit on the number of people, it opens up a dynamic space to store multiple information tables
	long long size;  //Number of people with real information
	long long capacity; //Address book capacity
};



int main()
{
    struct contact con = {};  //Create address book

    Initcon(&con); //Initialize address book

    int input = 0;
    printf("Please enter the command you want to operate:\n");
    do
    {
        remind(); //Menu prompt
        scanf("%d", &input);
        switch (input)
        {
        case Exit:
            save_con(&con);     //Save address book to folder
            free_con(&con); 	//Be sure to free up dynamic space
            printf("You have successfully exited the system!\n");
            break;
        case add:
            add_con(&con);
            printf("Information storage completed!\n Waiting for your next command:\n");
            break;
        case del:
            del_con(&con);
            printf("This person's information has been deleted!\n Waiting for your next command:\n");
            break;
        case search:
            search_con(&con);
            printf("Search succeeded,Waiting for your next command:\n");
            break;
        case modify:
            modify_con(&con);
            printf("Modification completed\n Waiting for your next command:\n");
            break;
        case show:
            printf("Details of the owner are as follows,Please check:\n");
            show_con(&con);
            printf("Show over,Waiting for your next command:\n");
            break;
        case sort:
            sort_con(&con);
            printf("Sorting succeeded\n Waiting for your next command:\n");
            break;
        default:
            printf("Your command is not in the menu bar,Please reselect:\n");
            break;
        }
    } while (input);

    return 0;
}

Here, the logical structure has been built, but can you modify it? For example, 0-6 in the switch case statement, can we replace it with a more meaningful sentence?

How? This is the benefit of enumeration

The revised contents are as follows:

#include <stdio.h>
struct information //Personal information form
{
	char name[20];//full name
	char sex[10]; //Gender
	int age;//Age
	char tele[15];//Telephone
	char address[40];//address
};

struct contact  //mail list
{
	struct information* info; //Because there is no limit on the number of people, it opens up a dynamic space to store multiple information tables
	long long size;  //Number of people with real information
	long long capacity; //Address book capacity
};

enum command   //Enumeration constant added
{
	Exit,
	add,
	del,
	search,
	modify,
	show,
	sort
};


int main()
{
    struct contact con = {};  //Create address book
    Initcon(&con); //Initialize address book
    int input = 0;
    printf("Please enter the command you want to operate:\n");
    do
    {
        remind(); //Menu prompt
        scanf("%d",&input);
        switch(input)
        {
            case Exit:
                save_con(&con);     //Save address book to folder
                free_con(&con); 	//Be sure to free up dynamic space
                printf("You have successfully exited the system!\n");
                break;
            case add:
                add_con(&con);
                printf("Information storage completed!\n Waiting for your next command:\n");
                break;
            case del:
                del_con(&con);
                printf("This person's information has been deleted!\n Waiting for your next command:\n");
                break;
            case search:
                search_con(&con);
                printf("Search succeeded,Waiting for your next command:\n");
                break;
            case modify:
                modify_con(&con);
                printf("Modification completed\n Waiting for your next command:\n");
                break;
            case show:
                printf("Details of the owner are as follows,Please check:\n");
                show_con(&con);
               	printf("Show over,Waiting for your next command:\n");
                break;
            case sort:
                sort_con(&con);
                printf("Sorting succeeded\n Waiting for your next command:\n");
                break;
            default:
                printf("Your command is not in the menu bar,Please reselect:\n");
                break;
        }
    }while(input);
    
    return 0;
}

③ Specific implementation of each module

1. Implementation of initcon initialization address book

When building the structure, we only created the address book, but the address book actually has nothing We need to give it an initial value

#include <stdlib.h>
void Initcon(struct contact* con)
{
    con->info = (struct information*)malloc(sizeof(struct information) * 4); //Open up personal information space
    if (con->info == NULL)
    {
        printf("Insufficient system capacity,Unable to increase address book capacity\n");
        return;
    }

    con->size = 0; //There are currently 0 stored information
    con->capacity = 4; //There are 4 storage spaces left in the current address book
}

2.remind menu making

Menu making is actually printing out the relevant information

void remind()
{
    printf(
        "******************************************************************\n"
        "******************************************************************\n"
        "*********************    0   Exit address book    ***********************\n"
        "*********************    1  Store relevant information   ***********************\n"
        "*********************    2  Delete related information   ***********************\n"
        "*********************    3  Find someone's information   ***********************\n"
        "*********************    4  Modify sb's information   ***********************\n"
        "*********************    5   show address book    ***********************\n"
        "*********************    6    Information sorting     ***********************\n"
        "******************************************************************\n"
        "******************************************************************\n"
    );
}

3.add_ Realization of con storing information

Storing information is to write in a person's name, gender, age, telephone number and address, that is, we need to update the structure struct information

At the same time, we know that once a message is added, the actual capacity size in the address book struct contact will increase by 1 The remaining capacity will be subtracted by 1

Most importantly, before we store information, we must not forget to check whether size is equal to capacity. If it is equal to capacity, we need to increase capacity

void add_con(struct contact* con)
{

    check_capacity(con); //This step is essential

    printf("Please enter the required storage name:\n");
    scanf("%s", con->info[con->size].name);
    printf("Please enter their gender:\n");
    scanf("%s", con->info[con->size].sex);
    printf("Please enter their age:\n");
    scanf("%s", con->info[con->size].age);
    printf("Please enter their phone number:\n");
    scanf("%s", con->info[con->size].tele);
    printf("Please enter their residential address:\n");
    scanf("%s",con->info[con->size].address);

    con->size++; //Number of people stored plus 1
}

1.check_ Implementation of capacity increasing function

When storing information, we need to check whether it is necessary to expand the capacity_ This is the function of capacity

void check_capacity(struct contact* con)
{
    if (con->size == con->capacity)
    {
        struct information* p = (struct information*)realloc(con->info, sizeof(struct information) * (con->capacity + 4));
        //Open up 4 more capacity at a time
        if (p == NULL)
        {
            printf("The system capacity is insufficient to continue to store information\n");
            return;
        }

        con->info = p;
        con->capacity += 4;
    }
}

4.del_ Implementation of con deleting information

To delete a person's information, it's very simple. Just know the person's name But how do we implement deletion with code?

Because we use dynamic memory arrays After deleting a person's information, a position will be vacant, and the probability of that position is in the middle

Do you want to move the following data forward after deletion? It's feasible, but it's troublesome

What can we do? Take the overwrite method, move the data forward directly, and then subtract 1 from size In this way, even if the last one still exists, we are behind

Even if you increase it, it will be covered

void del_con(struct contact* con)
{
    printf("What is the name of the person you want to delete:\n");
    char na[20] = "";
    int index = 0,i = 0;
    scanf("%s", na);

    for (i = 0; i < con->size - 1; i++)  //Find out where this person is. If it's at the back, you only need size - 1
    {
        if (!strcmp(con->info[i].name, na))
        {
            index = i;
            break;
        }
    }

    if ((i == con->size) && (strcmp(con->info[con->size - 1].name, na) != 0))
    {
        printf("This person does not exist!\n");
        return;
    }


    for (i = index; i < con->size-1; i++)  //Sequential coverage
    {
        con->info[i] = con->info[i + 1];
    }

    con->size -= 1; //Don't forget to subtract 1~~

}

5.search query module

Query, that is, query according to the name Required code and del_ Part of con is similar

void search_con(struct contact* con)
{
    printf("What is the name of the person you want to find:\n");
    char na[20] = "";
    scanf("%s",na);
    int i = 0;
    for(i = 0;i<con->size;i++)
    {
        if (!strcmp(con->info[i].name, na))
        {
            printf("The information is as follows:\n"
                "%4s\t%4s\t%4s\t%4s\t%4s\n ",
                "full name","Gender","Age","Telephone","address");

            printf("%s\t%s\t%s\t%s\t%s\n",
                con->info[i].name,con->info[i].sex,con->info[i].age,con->info[i].tele, con->info[i].address);
            
            break;
        }
    }

    if (i == con->size)
    {
        printf("This person does not exist\n");
    }
}

6.modify_ Implementation of con information modification

Information modification, as the name suggests, is to modify a certain information Search the name directly, and then modify the relevant information

void modify_con(struct contact* con)
{
    printf("Whose information do you want to modify:\n");
    char na[20] = "";
    scanf("%s", na);
    for (int i = 0; i < con->size; i++)
    {
        if (!strcmp(con->info[i].name, na))
        {
            printf("The name needs to be modified to: ");
            scanf("%s",con->info[i].name);
            printf("\n Sex is changed to:");
            scanf("%s", con->info[i].sex);
            printf("\n Age changed to:");
            scanf("%s", con->info[i].age);
            printf("\n The telephone number is modified to:");
            scanf("%s", con->info[i].tele);
            printf("\n Address changed to:");
            scanf("%s", con->info[i].address);
            printf("\n");
            break;
        }
    }
}

7.show show owner information

void show_con(struct contact* con)
{
    printf("The information is as follows:\n"
        "%4s\t%4s\t%4s\t%4s\t%4s\n",
        "full name", "Gender", "Age", "Telephone", "address");

    for (int i = 0; i < con->size; i++)
    {
        printf("%s\t%s\t%s\t%s\t%s\n",
            con->info[i].name, con->info[i].sex, con->info[i].age, con->info[i].tele, con->info[i].address);
    }
}

8.sort_con information sorting

Here's a little thought. It's not allowed to investigate the sorting library functions. How can we sort?

Selection sorting used by bloggers:

void swap(struct information* a, struct information* b)
{
    struct information p = {0};
    p = *a;
    *a = *b;
    *b = p;
}
void sort_con(struct contact* con)
{
    printf("Sort by what you want:\n"
        "Name gender age telephone address?\n:");
    char na[20] = "";
    scanf("%s", na);
    int i = 0, j = 0;
    for (i = 0; i < con->size - 1; i++)
    {
        int dex = i;

        if (!strcmp(na, "full name"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].name, con->info[j].name) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
        else if (!strcmp(na, "Gender"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].sex, con->info[j].sex) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
        else if (!strcmp(na, "Age"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].age, con->info[j].age) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
        else if (!strcmp(na,"Telephone"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].tele, con->info[j].tele) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
        else if (!strcmp(na, "address"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].address, con->info[j].address) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
    }
}

9.save_con saves the address book information

void save_con(struct contact* con)
{
    FILE* write = fopen("pp.txt","wb");
    if (!write)
    {
        printf("Insufficient system capacity,can't save\n");
        return;
    }

    fwrite(con->info,sizeof(struct information),con->size,write);
    fclose(write);
    write = NULL;
}

10.free_con free memory

void free_con(struct contact* con)
{
    free(con->info);
    con->info = NULL;
}

End

At this point, the whole address book is written

???

Is it really over??? Let's think carefully. What else is wrong

Yes, that is, although we saved the file, did we read the last saved content the next time we run the program? No

So we had a problem with initialization. We forgot to read the contents of the file during initialization

Modification:

void save_con(struct contact* con)
{
    FILE* write = fopen("pp.txt","wb");
    if (!write)
    {
        printf("Insufficient system capacity,can't save\n");
        return;
    }

    fwrite(con->info,sizeof(struct information),con->size,write);
    fclose(write);
    write = NULL;
}


void Initcon(struct contact* con)
{
    con->info = (struct information*)malloc(sizeof(struct information) * 4);
    if (con->info == NULL)
    {
        printf("Insufficient system capacity,Unable to increase address book capacity\n");
        return;
    }
    con->size = 0; //There are currently 0 stored information
    con->capacity = 4; //There are 4 storage spaces left in the current address book

    read_con(con);
}

end

Full code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct information //Personal information form
{
    char name[20];//full name
    char sex[10]; //Gender
    char age[10];//Age
    char tele[15];//Telephone
    char address[40];//address
};

struct contact  //mail list
{
    struct information* info; //Because there is no limit on the number of people, it opens up a dynamic space to store multiple information tables
    long long size;  //Number of people with real information
    long long capacity; //Address book remaining capacity
};

enum command   //Enumeration constant added
{
    Exit,
    add,
    del,
    search,
    modify,
    show,
    sort
};

void save_con(struct contact* con)
{
    FILE* write = fopen("pp.txt","wb");
    if (!write)
    {
        printf("Insufficient system capacity,can't save\n");
        return;
    }

    fwrite(con->info,sizeof(struct information),con->size,write);
    fclose(write);
    write = NULL;
}
void free_con(struct contact* con)
{
    free(con->info);
    con->info = NULL;
}
void check_capacity(struct contact* con)
{
    if (con->size == con->capacity)
    {
        struct information* p = (struct information*)realloc(con->info, sizeof(struct information) * (con->capacity + 4));
        //Open up 4 more capacity at a time
        if (p == NULL)
        {
            printf("The system capacity is insufficient to continue to store information\n");
            return;
        }

        con->info = p;
        con->capacity += 4;
    }
}

void read_con(struct contact* con)
{
    FILE* read = fopen("pp.txt","rb");
    if (read == NULL)
    {
        return;
    }
    int i = 0;
    while (fread(&(con->info[i++]), sizeof(struct information), 1, read))
    {
        check_capacity(con);  //Do not forget to check the capacity increase
        con->size++;
    }
}

void Initcon(struct contact* con)
{
    con->info = (struct information*)malloc(sizeof(struct information) * 4);
    if (con->info == NULL)
    {
        printf("Insufficient system capacity,Unable to increase address book capacity\n");
        return;
    }
    con->size = 0; //There are currently 0 stored information
    con->capacity = 4; //There are 4 storage spaces left in the current address book

    read_con(con);
}

void remind()
{
    printf(
        "******************************************************************\n"
        "******************************************************************\n"
        "*********************    0   Exit address book    ***********************\n"
        "*********************    1  Store relevant information   ***********************\n"
        "*********************    2  Delete related information   ***********************\n"
        "*********************    3  Find someone's information   ***********************\n"
        "*********************    4  Modify sb's information   ***********************\n"
        "*********************    5   show address book    ***********************\n"
        "*********************    6    Information sorting     ***********************\n"
        "******************************************************************\n"
        "******************************************************************\n"
    );
}


void add_con(struct contact* con)
{

    check_capacity(con); //This step is essential

    printf("Please enter the required storage name:\n");
    scanf("%s", con->info[con->size].name);
    printf("Please enter their gender:\n");
    scanf("%s", con->info[con->size].sex);
    printf("Please enter their age:\n");
    scanf("%s", con->info[con->size].age);
    printf("Please enter their phone number:\n");
    scanf("%s", con->info[con->size].tele);
    printf("Please enter their residential address:\n");
    scanf("%s",con->info[con->size].address);

    con->size++; //Number of people stored plus 1
}

void del_con(struct contact* con)
{
    printf("What is the name of the person you want to delete:\n");
    char na[20] = "";
    int index = 0,i = 0;
    scanf("%s", na);

    for (i = 0; i < con->size - 1; i++)  //Find out where this person is. If it's at the back, you only need size - 1
    {
        if (!strcmp(con->info[i].name, na))
        {
            index = i;
            break;
        }
    }

    if ((i == con->size) && (strcmp(con->info[con->size - 1].name, na) != 0))
    {
        printf("This person does not exist!\n");
        return;
    }


    for (i = index; i < con->size-1; i++)  //Sequential coverage
    {
        con->info[i] = con->info[i + 1];
    }

    con->size -= 1; //Don't forget to subtract 1~~

}

void search_con(struct contact* con)
{
    printf("What is the name of the person you want to find:\n");
    char na[20] = "";
    scanf("%s",na);
    int i = 0;
    for(i = 0;i<con->size;i++)
    {
        if (!strcmp(con->info[i].name, na))
        {
            printf("The information is as follows:\n"
                "%4s\t%4s\t%4s\t%4s\t%4s\n ",
                "full name","Gender","Age","Telephone","address");

            printf("%s\t%s\t%s\t%s\t%s\n",
                con->info[i].name,con->info[i].sex,con->info[i].age,con->info[i].tele, con->info[i].address);
            
            break;
        }
    }

    if (i == con->size)
    {
        printf("This person does not exist\n");
    }
}

void modify_con(struct contact* con)
{
    printf("Whose information do you want to modify:\n");
    char na[20] = "";
    scanf("%s", na);
    for (int i = 0; i < con->size; i++)
    {
        if (!strcmp(con->info[i].name, na))
        {
            printf("The name needs to be modified to: ");
            scanf("%s",con->info[i].name);
            printf("\n Sex is changed to:");
            scanf("%s", con->info[i].sex);
            printf("\n Age changed to:");
            scanf("%s", con->info[i].age);
            printf("\n The telephone number is modified to:");
            scanf("%s", con->info[i].tele);
            printf("\n Address changed to:");
            scanf("%s", con->info[i].address);
            printf("\n");
            break;
        }
    }
}

void show_con(struct contact* con)
{
    printf("The information is as follows:\n"
        "%4s\t%4s\t%4s\t%4s\t%4s\n",
        "full name", "Gender", "Age", "Telephone", "address");

    for (int i = 0; i < con->size; i++)
    {

        printf("%s\t%s\t%s\t%s\t%s\n",
            con->info[i].name, con->info[i].sex, con->info[i].age, con->info[i].tele, con->info[i].address);
    }
}

void swap(struct information* a, struct information* b)
{
    struct information p = {0};
    p = *a;
    *a = *b;
    *b = p;
}

void sort_con(struct contact* con)
{
    printf("Sort by what you want:\n"
        "Name gender age telephone address?\n:");
    char na[20] = "";
    scanf("%s", na);
    int i = 0, j = 0;
    for (i = 0; i < con->size - 1; i++)
    {
        int dex = i;

        if (!strcmp(na, "full name"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].name, con->info[j].name) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
        else if (!strcmp(na, "Gender"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].sex, con->info[j].sex) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
        else if (!strcmp(na, "Age"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].age, con->info[j].age) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
        else if (!strcmp(na,"Telephone"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].tele, con->info[j].tele) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
        else if (!strcmp(na, "address"))
        {
            for (j = i + 1; j < con->size; j++)
            {
                if (strcmp(con->info[dex].address, con->info[j].address) > 0)
                {
                    dex = j;
                }
            }
            swap(&con->info[dex], &con->info[i]);
        }
    }
}
int main()
{
    struct contact con = {0};  //Create address book

    Initcon(&con); //Initialize address book

    int input = 0;
    printf("Please enter the command you want to operate:\n");
    do
    {
        remind(); //Menu prompt

        scanf("%d", &input);

        switch (input)
        {
        case Exit:
            save_con(&con);     //Save address book to folder
            free_con(&con); 	//Be sure to free up dynamic space
            printf("You have successfully exited the system!\n");
            break;
        case add:
            add_con(&con);
            printf("Information storage completed!\n Waiting for your next command:\n");
            break;
        case del:
            del_con(&con);
            printf("This person's information has been deleted!\n Waiting for your next command:\n");
            break;
        case search:
            printf("This person's information is as follows:\n");
            search_con(&con);
            printf("Search succeeded,Waiting for your next command:\n");
            break;
        case modify:
            modify_con(&con);
            printf("Modification completed\n Waiting for your next command:\n");
            break;
        case show:
            printf("The details of the stored person are as follows,Please check:\n");
            show_con(&con);
            printf("Show over,Waiting for your next command:\n");
            break;
        case sort:
            sort_con(&con);
            printf("Sorting succeeded\n Waiting for your next command:\n");
            break;
        default:
            printf("Your command is not in the menu bar,Please reselect:\n");
            break;
        }
    } while (input);

    return 0;
}

Topics: C