C language implementation of address book (static version)

Posted by keystroke on Tue, 28 Sep 2021 06:19:45 +0200

Preface: bloggers have written two interesting small projects before: tic-tac-toe and mine clearance Next, the blogger continues to update a small project - address book, including three versions, static version, dynamic version and file saving version. Next, let's explain how to implement the static version.

catalogue

1, Overview of static address book

2, Implementation of static address book interface function

1. Basic structure of static address book

2. Game framework (for users to choose)

3. Initialize address book

4. Print address book

5. Increase in membership

6. Judge whether the address book is empty

7. Find function

8. Delete the specified contact

9. Find the designated contact

10. Modify the designated contact

11. Sort contacts by name

12. Sort contacts by age

13. Empty the address book

1, Overview of static address book

Static address book: fixed length array is used, that is, the length of the array cannot be changed. We can set the number of members that can be recorded in the address book to 1000.

2, Implementation of static address book interface function

file namefunction
Contact.cImplementation of address book function interface
Contact.hMacro definition, header file, declaration of interface function
test.cFunction interface test

1. Basic structure of static address book

An address book is a structure.

Contains: 1. Address book member array. Each address book member is a structure, including address, name, age, gender, address and telephone.

          2. Variable indicating the number of address book members.

Note: in order to change the size of the address book in order, it is recommended to use the macro definition

//Note that the macro definition should not be followed by a semicolon!!!! Otherwise there will be problems
#define NAME_MAX 30 	// Maximum length of name
#define SEX_MAX 5 		// Gender maximum length
#define TELE_MAX 12 	// Maximum telephone length
#define ADDR_MAX 30 	// Maximum address length

#define MAX 1000 	// The total number of members in the address book array

typedef struct PeoInfo
{
	char name[NAME_MAX];
	int age;
	char sex[SEX_MAX];
	char addr[ADDR_MAX];
	char tele[TELE_MAX];
}PeoInfo;

struct Contact	//mail list
{
	PeoInfo data[MAX];	//Structure member array
	int size;	//Indicates the number of members contained in the address book and controls the subscript of the array
};

2. Game framework (for users to choose)

enum Option
{
	EXIT,
	ADD,
	DEL,
	SEARCH,
	MODIFY,
	SHOW,
	DESTORY,
};
void menu()
{
	printf("******************************\n");
	printf("****  1. add     2. del  *****\n");
	printf("****  3. search  4. modify****\n");
	printf("****  5. show    6. Destory   ***\n");
	printf("****  0. exit               **\n");
	printf("******************************\n");
}
int main()
{
	int input = 0;
	struct Contact con;	//Create an address book containing MAX structure members
	InitContact(&con);	//Initialize address book
	do
	{
		menu();
		printf("Please select->\n");
		scanf("%d", &input);
		switch (input)
		{
		case ADD:
			ADDContact(&con);
			break;
		case DEL:
			DelContact(&con);
			break;
		case SEARCH:
			SearchContact(&con);
			break;
		case MODIFY:
			ModifyContact(&con);
			break;
		case SHOW :
			ShowContact(&con);
			break;
		case DESTORY:
			DesContact(&con);
			break;
		case EXIT:
			printf("Exit succeeded! Welcome to use again!\n");
			break;
		default:
			printf("Selection error,Please reselect\n");
			break;
		}
	} while (input);
	return 0;
}

3. Initialize address book

Initializing the address book member array with memset

Writing 1: size of each member * number of members  

void InitContact(struct Contact* ps)
{
	assert(ps);
	//There was no data at first
	memset(ps->data, 0, sizeof(PeoInfo) * MAX);	//The address book member array is initialized to 0
	ps->size = 0;//The default member is 0
}

Writing method 2: the array is placed separately in sizeof - > the size of the whole array is calculated  

//Writing method 2
void InitContact(struct Contact* ps)
{
	memset(ps->data, 0, sizeof(ps->data));	
//PS - > data gets the array name of the PenInfo array in the address book
//The array list is placed inside sizeof, and the size of the entire array is calculated
	ps->size = 0;
}

4. Print address book

In order to be more intuitive, we can also print the title. By traversing the address book member array, the members can be printed.

//This is a right alignment. If you want to align left - > -% 30d, add a sign in front of% and a minus sign in front of% numbers
void ShowContact(struct Contact* ps)
{
	int i = 0;
	//Print title
    printf("%15s\t%5s\t%8s\t%15s\t%30s\t\n\n", "name", "age", "sex", "tele", "addr");

	//Prints the contents of each structure member in the array
	for (i = 0; i < ps->size; i++)
	{
		printf("%15s\t%5d\t%8s\t%15s\t%30s\n",
			ps->data[i].name,
			ps->data[i].age,
			ps->data[i].sex,
			ps->data[i].tele,
			ps->data[i].addr);
	}
}

5. Increase in membership

Writing method 1: directly operate on the address book member array

void ADDContact(struct Contact* ps)
{
	//First determine whether the address book is full
	if (ps->size == MAX)
	{
		printf("The address book is full\n");
	}
	else
	{
		printf("Please enter your first name:");
		scanf("%s", ps->data[ps->size].name);	//Array name is not used&
		printf("Please enter age: ");
		scanf("%d", &(ps->data[ps->size].age));
		printf("Please enter the address:");
		scanf("%s", ps->data[ps->size].addr);
		printf("Please enter the number:");
		scanf("%s", ps->data[ps->size].tele);
		printf("Please enter gender:");
		scanf("%s", ps->data[ps->size].sex);

		printf("Added successfully\n");
		ps->size++;	//Added a member, size++
	}
}

  Writing method 2: first create a temporary structure member, and then assign it to the PS - > size position in the address book structure array after assignment

//Add member 2:
void ADDContact(struct Contact* ps)
{
	PeoInfo tmp = { 0 };
	//First determine whether the address book is full
	if (ps->size == MAX)
	{
		printf("The address book is full\n");
	}
	else
	{
		printf("Please enter your first name:");
		scanf("%s", tmp.name);	//Array name is not used&
		printf("Please enter age: ");
		scanf("%d", &(tmp.age));
		printf("Please enter the address:");
		scanf("%s", tmp.addr);
		printf("Please enter the number:");
		scanf("%s", tmp.tele);
		printf("Please enter gender:");
		scanf("%s", tmp.sex);

		ps->data[ps->size] = tmp;
		printf("Added successfully\n");
		ps->size++;
	}
}

6. Judge whether the address book is empty

Because the size flag indicates the number of members in the address book, you can know whether the address book is empty by judging whether the size is 0

//If it is empty, the judgment is true and 1 is returned
bool EmptyContact(struct Contact* ps)
{
    return ps->size == 0;
}

7. Find function

Because the subsequent deletion of the specified contact and the change of the information of the specified contact need to be searched, the search function can be encapsulated separately

If found, return the corresponding subscript. If not found, return - 1

Because it is not modified, you can add const modification

Method: traverse the structure member array to find

int FindContactByName(const struct Contact* ps,const char*name )
{
    //Traversal search
    int i = 0;
    for(i = 0;i< ps->size;i++)
    {
        if( strcmp(name,ps->data[i].name) == 0)
        {
            //Return subscript
            return i;
        }
    }
    return -1;
}

8. Delete the specified contact

Note: delete contact - > start from this location, and the subsequent data will be overwritten

If the address book is empty, it will not be deleted and will be returned directly

void DelContact(struct Contact* ps)
{
	if (EmptyContact(ps))
	{
		printf("The address book is empty and cannot be deleted\n");
		return ;
	}
	char name[NAME_MAX] = { 0 };	//Used to store the name of the specified contact to be deleted
	printf("Please enter the name of the person to delete:>");
	scanf("%s",name);
	//lookup
	int pos = FindContactByName(ps, name);
	if (pos == -1)
	{
		printf("The specified contact does not exist\n");
	}
	else
	{
		//Delete operation
		//Start at the pos position and cover the rear forward
		int i = 0;
		for (i = pos; i < ps->size - 1; i++)
		{
			ps->data[i] = ps->data[i + 1];
		}
		//Deleted element, size--
		ps->size--;
		printf("Delete succeeded\n");
	}
}

9. Find the designated contact

Method: enter the name of the contact to be searched, call the search function to search, if found, return the corresponding subscript, and print the corresponding information of the contact corresponding to the subscript

void SearchContact(const struct Contact* ps)
{
    char name[NAME_MAX] = {0};
    printf("Enter the contact you want to find:>");
    scanf("%s",name);
    int pos  =FindContactByName(ps,name);
    if(pos == -1)
    {
        printf("The contact you are looking for does not exist\n");
    }
    else
    {
        // Print the information corresponding to the contact
		//Print title       
        printf("%15s\t%5s\t%8s\t%15s\t%30s\t\n\n", "name", "age", "sex", "tele", "addr");
		printf("%15s\t%5d\t%8s\t%15s\t%30s\n",
			ps->data[pos].name,
			ps->data[pos].age,
			ps->data[pos].sex,
			ps->data[pos].tele,
			ps->data[pos].addr);
	}
    }
}

10. Modify the designated contact

Method: enter the name of the contact to be searched, call the search function to search, find the returned corresponding subscript, and then modify the content of the corresponding array subscript

void ModifyContact(struct Contact* ps)
{
	char name[NAME_MAX] = { 0 };
	printf("Please enter the name of the person to modify:>");
	scanf("%s", name);
	int pos = FindContactByName(ps, name);
	if (-1 == pos)
	{
		printf("No one was found\n");
	}
	else
	{
		printf("Please enter a new name:");
		scanf("%s", ps->data[pos].name);	//Array name is not used&
		printf("Please enter a new age: ");
		scanf("%d", &(ps->data[pos].age));
		printf("Please enter a new address:");
		scanf("%s", ps->data[pos].addr);
		printf("Please enter a new number:");
		scanf("%s", ps->data[pos].tele);
		printf("Please enter a new gender:");
		scanf("%s", ps->data[pos].sex);
	}
}

11. Sort contacts by name

Equivalent to string comparison - > using strcmp

Two methods can be used here: bubble sort or qsort sort

About qsort: Detailed explanation of qsort function

  Compare the member names in the address book member array!!!

void SortContact(struct Contact* pcon)
{
  int i, j;
  struct PeoInfo tmp;
  for(i = 0; i < pcon->sz - 1; i++)
 {
    for(j = 0; j < pcon->sz - 1 - i; j++)
   {
      if(0 < strcmp(pcon->data[j].name, pcon->data[j + 1].name))
     {
        tmp = pcon->data[j];
        pcon->data[j] = pcon->data[j + 1];
        pcon->data[j + 1] = tmp;
     }
   }
 }
}
void SortContactByName(struct Contact* ps)
{
	qsort(ps->data, ps->size, sizeof(ps->data[0]), cmp_ContactByName);
}

int cmp_ContactByName(const void* e1, const void* e2)
{
	return strcmp( ((struct PeoInfo*)e1)->name, ((struct PeoInfo*)e2)->name);
}
//be careful
//  ((struct peoinfo *) e1) - > name should be enclosed,
//  (struct peoinfo *) e1 - > name is wrong

12. Sort contacts by age

Note that the member array PS - > data in the address book is sorted: the type of each element is struct PenInfo (structure member type), and the number to be sorted is PS - > size

The size flag indicates the number of address book members

Comparison function: the age of members is compared

void SortContact(struct Contact* ps)
{
	qsort(ps->data, ps->size, sizeof(ps->data[0]), cmp_ContactbyAge);
}

int cmp_ContactbyAge(const void* e1, const void* e2)
{
	return ((struct PeoInfo*)e1)->age - ((struct PeoInfo*)e2)->age;
}

13. Empty the address book

Empty address book: equivalent to reinitialization of heap address book

void ClearContact(Contact* pcon)
{
    InitContact(pcon);
}

3, Disadvantages of static address book

Limited membership: it is easy to cause space waste / insufficient space.

In order to solve this problem, in the next article, bloggers will take you to learn about dynamic address book

Thank you very much for seeing here, ~ if it helps you, welcome to give the blogger a three company~

Topics: C C++