当前位置:网站首页>Detailed explanation of C language "address book"
Detailed explanation of C language "address book"
2022-07-18 15:28:00 【Orange cat】
Catalog
Mail list
Implement an address book , Record a person's information , And man is a complex object
Human information : name 、 Age 、 Gender 、 Telephone 、 Address, etc .
You can use a structure to contain human information together and encapsulate a structure type
Function directory of address book
The functions of the address book are 7 Kind of :
- Depositor's information
- Add contacts
- Delete designated contact
- Find contacts
- Modify the contact's information
- Sort contacts
- Show contact information
- Exit address book
- Source code file :
test.cTesting capabilitiescontact.cRealization of address book functioncontact.hDeclaration of type
Realization of address book
Structure type of the information of the creator
The first step is to encapsulate the structure type of a person's information
Because the name of the encapsulated structure type is too long , It's too troublesome to always write
Yes struct PeoInfo the typdef Type renaming struct PeoInfp Change to PeoInfp
// Human information
typedef struct PeoInfo
{
char name[20]; // name
int age; // Age
char sex[10]; // Gender
char tele[13];// Telephone
char addr[30];// Address
}PeoInfo;
- The above values will be used frequently in the future , It can be used #define To define , Easy to modify later

Open up the space of address book
After defining the structure type above , Also create a framework , Just like guessing numbers 、 Like minesweeping , Then define variables to open up the space required by the address book
After that, if you add contacts to the address book 、 Delete designated contact 、 Find contacts and other operations
The information and number of people in the address book are changing , You need a variable to record how many personal information is in the address book
PeoInfo data[100] and count Add the two variables together to maintain the address book 
- If you put it in the main function ,
PeoInfo data[100]After adding a person's information , thatcountShould it also be able to change
Is it too troublesome to change it often , So can you putPeoInfo data[100]andcountEncapsulated in a structure
There is the following writing :
hold PeoInfo data[100] and count Put it all together , It will be more convenient to modify and find in the future
Because the name of the encapsulated structure type is too long , It's too troublesome to always write
Yes struct Contact the typdef Type renaming struct Contact Change to Contact
// Mail list
typedef struct Contact
{
PeoInfo data[100];// Depositor's information
int count;// Record the number of person information in the address book
}Contact;
Initialization of address book
If you want to initialize , Just define the address book
- Initialize with a function

- First in
contact.hType declaration in the document , And then againcontact.cIn the file
The function parameter passes the address , So use a pointer to receive ,ContactIt's the type - The second use
memsetFunction to initialize ,memsetIs the memory setting
sizeof Calculate the size of the structure , The result is in bytes
// Initialize address book
void InitContact(Contact* pc)
{
pc->count = 0;
memset(pc->data, 0, sizeof(pc->data));
}
The above initializes all spaces as 0 了
The initialization part is finished
Add contacts
The above method of function addressing , Sent the address to pc Variable , amount to pc Points to the address book with the subscript count The address of
The next step is to add contact information , The premise of adding contacts is that the space of the address book is not full , When it is full, it cannot be increased , Go straight back to (return)
So we need to add a judgment first
MAX yes #define The global variables defined are 100
The address book has no more space than 100, Take the next step , Add contact information 
- The information stored each time is put into
conindataArray of , Subscript to becountThe location of
Human information has 5 Kind of , Input separately : - Input name :
pc->data[pc->count].namepc->dataIs pointing to an arraypc->countIs the subscript representing the array. nameIs a member that points to a structure , andnameIs the address of the first element of the array , So there's no need to& - Enter the age : Because age is
Shaping variables, So go ahead with&operation - The remaining three are the same as the first , So there's no need to
& - Finally, after success ,
countwant++
Display and print
After adding success , Next is display and print , Check whether the printed value is correct
It is still implemented in a functional way
Print information , It's printing count Personal information , Direct use for Loop printing \t It's horizontal tabulation
void ShowContact(const Contact* pc)
{
assert(pc);
int i = 0;
for (i = 0; i < pc->count; i++)
{
printf("%20s\t%3d\t%5s\t%13s\t%30s\n", pc->data[i].name,
pc->data[i].age,
pc->data[i].sex,
pc->data[i].tele,
pc->data[i].addr);
}
}
So let's test that out :
When printing above , No title , It's not easy to understand
The following is to add a title to the previous line of the output
If you want to align the format to the left , Just add - Number 
Display the printed information :

Delete Contact
Add contacts , Then the next step is to delete the contact ,
- First step The prerequisite for deleting a contact is that the address book is not empty , There is also the information of this contact , So first judge
- The second step To delete a contact, you must first find the contact , Then judge , The last thing is to delete
Search is to directly encapsulate a function (FindByName). You need to pass two parameters ( Mail list 、 Parameters to find )
The function is to return the subscript of this number if found , No return found -1
int FindByName(Contact* pc, char name[])
{
assert(pc);
int i = 0;
for (i = 0; i < pc->count; i++)
{
if (0 == strcmp(pc->data[i].name, name))
{
return i;
}
}
return -1;
}
- The third step Just delete
ret It is the subscript of the contact name to be deleted found by the above function ,pc->count-1Is to prevent the last 99 Elements are out of bounds
The last element does not need to be changed , Because in the endpc->coun--It is indirectly deleted

So let's test that out :
Find contacts
It's easier to find contacts , I wrote in deleting contacts before
The idea is to first judge whether the person you want to find exists , Call the function written before FindByName
Then output in format 
So let's test that out :
Modify contact
There are few steps to modify contacts
First step : First enter the name of the person you want to modify
The second step : Find the name of the modifier , Directly call the function to find
The third step : Fill in the information of the modifier 
Sort
Sort directly qsort function
The first parameter represents the address of the first element (pc->data)
The second parameter is the number of elements (pc->count)
The third is the size of the array (sizeof(PeoInfo)), Or you could write it as (pc->data[0])
The fourth is the way of sorting
int by_age(const void* e1, const void* e2)
{
return ((PeoInfo*)e1)->age - ((PeoInfo*)e2)->age;
}
void SortContact(Contact* pc)
{
assert(pc);
qsort(pc->data, pc->count, sizeof(PeoInfo), by_age);
printf(" Sort success \n");
}
So let's test that out :
- Written here, all functions are fully realized
Source code
test.c
#include"contact.h"
void menu()
{
printf("**********************************************\n");
printf("******* 1. add( increase ) 2.del( Delete ) ******\n");
printf("******* 3. search( lookup ) 4.modify( Change ) ******\n");
printf("******* 5. show( Show ) 6. sort( Sort ) ******\n");
printf("******* 0. exit( sign out ) ******\n");
printf("**********************************************\n");
}
int main()
{
int input = 0;
Contact con;
// Initialize address book
InitContact(&con);
do
{
menu();
printf(" Please select :");
scanf("%d", &input);
switch (input)
{
case 1:
Addcontact(&con);
break;
case 2:
DelContact(&con);
break;
case 3:
SearContact(&con);
break;
case 4:
ModifyContact(&con);
break;
case 5:
ShowContact(&con);
break;
case 6:
SortContact(&con);
ShowContact(&con);// Show contacts
break;
case 0:
printf(" Exit address book \n");
break;
default:
printf(" Wrong choice \n");
break;
}
} while (input);
}
Contact.c
#include"contact.h"
// Initialize address book
void InitContact(Contact* pc)
{
assert(pc);
pc->count = 0;
memset(pc->data, 0, sizeof(pc->data));
}
// Add contacts
void Addcontact(Contact* pc)
{
assert(pc);
if (pc->data == MAX)
{
printf(" The address book is full \n");
return;
}
printf(" Please enter the name of the contact :");
scanf("%s",pc->data[pc->count].name);
printf(" Please enter age :");
scanf("%d", &(pc->data[pc->count].age));
printf(" Please enter gender :");
scanf("%s", pc->data[pc->count].sex);
printf(" Please input the phone number :");
scanf("%s", pc->data[pc->count].tele);
printf(" Please enter the address :");
scanf("%s", pc->data[pc->count].addr);
pc->count++;
printf(" Increase success \n");
}
// Print information
void ShowContact(const Contact* pc)
{
assert(pc);
int i = 0;
printf("%-20s\t%-4s\t%-5s\t%-13s\t%-30s\n", " name ", " Age ", " Gender ", " Telephone ", " Address ");
for (i = 0; i < pc->count; i++)
{
printf("%-20s\t%-4d\t%-5s\t%-13s\t%-30s\n", pc->data[i].name,
pc->data[i].age,
pc->data[i].sex,
pc->data[i].tele,
pc->data[i].addr);
}
}
static int FindByName(Contact* pc, char name[])
{
assert(pc);
int i = 0;
for (i = 0; i < pc->count; i++)
{
if (0 == strcmp(pc->data[i].name, name))
{
return i;
}
}
return -1;
}
// Delete Contact
void DelContact(Contact* pc)
{
assert(pc);
char name[MAX_NAME] = {
0 };
if (pc->count == 0)
{
printf(" Address book is empty , No information can be deleted \n");
return;
}
printf(" Please enter the name of the contact to delete :");
scanf("%s", &name);
//1. lookup
int ret = FindByName(pc, name);
if (ret == -1)
{
printf(" The person to delete does not exist \n");
}
//2. Delete
int i = 0;
for (i = ret; i < pc->count-1; i++)
{
pc->data[i] = pc->data[i + 1];
}
pc->count--;
printf(" Delete successful \n");
}
// Find contacts
void SearContact(Contact* pc)
{
assert(pc);
char name[MAX_NAME] = {
0 };
printf(" Please enter the name of the contact you want to find :");
scanf("%s", &name);
// Judge
int ret = FindByName(pc, name);
if (ret == -1)
{
printf(" The person you're looking for doesn't exist \n");
return;
}
// Print
printf("%-20s\t%-4s\t%-5s\t%-13s\t%-30s\n", " name ", " Age ", " Gender ", " Telephone ", " Address ");
printf("%-20s\t%-4d\t%-5s\t%-13s\t%-30s\n",
pc->data[ret].name,
pc->data[ret].age,
pc->data[ret].sex,
pc->data[ret].tele,
pc->data[ret].addr);
}
// Modify contact
void ModifyContact(Contact* pc)
{
assert(pc);
char name[MAX_NAME] = {
0 };
printf(" Please enter the name of the contact to be modified :");
scanf("%s", &name);
// lookup
int ret = FindByName(pc, name);
if (ret == -1)
{
printf(" The person to modify does not exist \n");
return;
}
// Modify the information
printf(" Please fill in the modification information \n");
printf(" Please enter the name of the contact :");
scanf("%s", pc->data[ret].name);
printf(" Please enter age :");
scanf("%d", &(pc->data[ret].age));
printf(" Please enter gender :");
scanf("%s", pc->data[ret].sex);
printf(" Please input the phone number :");
scanf("%s", pc->data[ret].tele);
printf(" Please enter the address :");
scanf("%s", pc->data[ret].addr);
printf(" Modification successful \n");
}
int by_age(const void* e1, const void* e2)
{
return ((PeoInfo*)e1)->age - ((PeoInfo*)e2)->age;
}
// Sort
void SortContact(Contact* pc)
{
assert(pc);
qsort(pc->data, pc->count, sizeof(PeoInfo), by_age);
printf(" Sort success \n");
}
Contact.h
// The header file
#include<stdio.h>
#include<string.h>
#include<assert.h>
#define MAX 100
#define MAX_NAME 20
#define MAX_SEX 10
#define MAX_TELE 13
#define MAX_ADDR 30
// Structure class declaration
// Human information
typedef struct PeoInfo
{
char name[MAX_NAME]; // name
int age; // Age
char sex[MAX_SEX]; // Gender
char tele[MAX_TELE];// Telephone
char addr[MAX_ADDR];// Address
}PeoInfo;
// Mail list
typedef struct Contact
{
PeoInfo data[MAX];// Depositor's information
int count;// Record the number of person information in the address book
}Contact;
// Initialization of address book
void InitContact(Contact* pc);
// Add contacts to the address book
void Addcontact(Contact* pc);
// Print address book information
void ShowContact(const Contact* pc);
// Delete Contact
void DelContact(Contact * pc);
void DelContact(Contact* pc);
// Find contacts
void SearContact(Contact* pc);
// Modify contact information
void ModifyContact(Contact* pc);
// Sort
void SortContact(Contact* pc);
summary :
At present, we have realized a simple address book , Then we will rewrite a dynamic version and a file version
边栏推荐
- Vulnhub - dc6 Learning Notes
- How should Amazon sellers prevent association? Don't cut the bill! (detailed explanation of evaluation self support number)
- Mobile communication helps the new move of summer grain storage, and scientific and technological means are more effective
- GooglePhoto设置壁纸----壁纸裁剪界面配置
- RMAN detailed tutorial (I) -- basic command code
- 「TakinTalks」_ If faults occur frequently, how to do a good job in system stability?
- The bottom logic of learning essence
- Go 原生插件使用问题全解析
- (cvpr-2022) Lagrangian motion analysis and perspective embedding for improved gait recognition
- 分布式笔记(01)— 分布式 CAP 理论及原理
猜你喜欢

Soft exam (intermediate software designer) exam information

Symbolic naming analysis in reinforcement learning

第三篇章:运行时数据区——独立空间

86触摸开关/台扇/空调/智能家居/家电等,低功耗高抗干扰3键3路3通触摸IC-VK3603 ESOP8,性能稳定,灵敏度可调

【日常训练】515. 在每个树行中找最大值

Vulnhub-DC9学习笔记

Select statement if else

ACL 2022 | argument pair extraction based on reading comprehension

Kingbasees v8r6 ksql turn off auto submit

【LeetCode】10. Maximum subarray · maximum subarray sum
随机推荐
【LeetCode】10. Maximum subarray · maximum subarray sum
el-input-number禁用科学计数无果,换成el-input(type=“number“)
Vulnhub-DC9学习笔记
How should Amazon sellers prevent association? Don't cut the bill! (detailed explanation of evaluation self support number)
RMAN detailed tutorial (II) -- backup, inspection, maintenance, recovery
STM32 application development practice tutorial: human machine interface application development with interactive function
Characteristics of Lora technology in wireless communication
Vulnhub-dc6 learning notes
【LeetCode】11. Lowest common ancestor of a binary search tree
重新认识你的NFT
21JVM(1)
What is a recommendation system?
(cvpr-2022) Lagrangian motion analysis and perspective embedding for improved gait recognition
Could not get lock /var/lib/dpkg/lock-frontend
Vulnhub-dc5学习笔记
亚马逊卖家该如何做好防关联?不砍单!(测评自养号详解)
QT learning diary 16 - qfile file reading and writing
86触摸开关/台扇/空调/智能家居/家电等,低功耗高抗干扰3键3路3通触摸IC-VK3603 ESOP8,性能稳定,灵敏度可调
2022 robocom world robot developer competition - undergraduate group (provincial competition) T4, T5
Special testing of mobile applications [reprint ~ Test Engineer full stack technology advancement and practice]