当前位置:网站首页>[C language implementation of address book] takes you through the key and difficult points of C language
[C language implementation of address book] takes you through the key and difficult points of C language
2022-04-21 12:23:00 【Want to make money】
Today opened a new column
In this column , I will write some small projects , Similar to the curriculum design required in the school , Please support !
List of articles
well , I don't say much nonsense , Let's start with the text
One 、 Project requirement
use C Language to write an address book program , It is required to be able to realize the of contact information Add or delete check change 、 Sort 、 Empty , Save contact information to a file , The next time you use it, you can read the information in the file .
Two 、 Implementation of various functions in the project
To realize various functions of the address book , You have to define a series of related functions , In this project , I used to 13 A function , Let's introduce one by one
First, let's define two structures
typedef struct PeoInfo
{
// Create contact information structure
char name[NAME_MAX];
char tele[TEL_MAX];
char addr[ADDR_MAX];
char sex[SEX_MAX];
int age;
}PeoInfo;
The first structure contains the basic information of the contact ( name , Telephone , Address , Gender , Age )
about char The size of the type array , I defined it in advance as a macro , The advantage of this is When you change the size of the array later , Just change the corresponding macro

The last two macros above represent the initial capacity of the address book and the increment of each capacity increase
To save memory , Every time the address book is full , The program will add capacity to it , Increase the space of two contact information at a time
The second structure contains the position of the first structure variable , Address book capacity and number of contacts saved in the address book
typedef struct
{
// The address of the contact information structure and the capacity of the address book 、 The current number of contacts is stored in the structure
PeoInfo* data;
int capacity;
int size;
}contact;
For your convenience , Here's a brief explanation :

as everyone knows , When transferring parameters to a structure , Address transmission is much better than the whole structure , Because there is no need to open up a large space , Here, storing the position of the first structure into the second structure also has this function
In the second structure capacity and size Indicates the capacity of the address book and the number of saved contacts respectively
well , Let's start with the function !!!
Function one :init_contact( Initialize the address book )
When I first started the program , We need to initialize the address book , In the process , The memory of three contact information sizes will be requested for the address book , And set the number of saved contacts to 0
void init_contact(contact* p)
{
assert(p);// Assertion ,p Not null pointer
p->data = (PeoInfo*)malloc(sizeof(PeoInfo) * CAPACITY);// Open up three structure size spaces for the address book
if (p == NULL)
{
printf(" initialization failed \n");
return;
}
p->size = 0;
p->capacity = CAPACITY;
}
Function two :check_contact( Check that the address book is full , Ruoman , Then increase the capacity )
int check_contact(contact* p)// Check that the address book is full , If it is full, increase the capacity
{
assert(p);
if (p->size == p->capacity)
{
printf(" The address book is full , Increase capacity \n");
// Add two new contact information space at a time
PeoInfo* tmp = (contact*)realloc(p->data, (p->size + ZENG) * sizeof(PeoInfo));
if (tmp == NULL)
{
printf(" Capacity increase failed \n");
return 0;
}
p->data = tmp;
p->capacity += ZENG;
return 1;
}
}
The illustration :


Remember to be right after capacity increase capacity+ZENG
Function three :locate( Search for 、 Delete 、 Locate the modified contact , Find its place in the address book )
int locate(char* name,contact* p)// Find the position of the contact to be operated in the structure array
{
assert(p);
int i = 0;
for (i = 0; i < p->size; i++)
{
if ((strcmp(name, p->data[i].name)) == 0)
{
return i;
}
}
if (i == p->size)
{
return 0;
}
}
The above code traverses the address book information , Until you find a contact , If found, the index of the contact in the structure array will be returned , Go back if you can't find it 0, This process is written as an independent function to facilitate the call of other functions , One time encapsulation , Multiple calls
Function four :add_contact( Add contact information )
void add_contact(contact* p)// Add a Contact
{
assert(p);
if (check_contact(p) == 0)
{
// Judge whether the capacity increase fails when the address book is full
printf(" The address book is full , Capacity increase failed \n");
return;
}
printf(" Please enter a name :>");
scanf("%s", p->data[p->size].name);
printf(" Please enter age :>");
scanf("%d", &p->data[p->size].age);
printf(" Please enter gender :>");
scanf("%s", p->data[p->size].sex);
printf(" Please input the phone number :>");
scanf("%s", p->data[p->size].tele);
printf(" Please enter the address :>");
scanf("%s", p->data[p->size].addr);
printf(" Add success \n");
p->size++;
}
To add contacts , First of all, it is necessary to judge whether the address book is full , If it is full, increase the capacity , Finally, don't forget to size++
Running effect :

Function five :dele_contact( Delete Contact )
void dele_contact(contact* p)// Delete Contact
{
assert(p);
char name[NAME_MAX];
printf(" Please enter the name of the person you want to delete :>");
scanf("%s", name);
int pos = locate(name, p);
if (pos == 0)
{
printf(" The contact does not exist !\n");
return;
}
else
{
// Move the contact position behind the contact to be deleted forward in turn , Overwrite this contact
for (int i = pos; i < p->size; i++)
{
p->data[i] = p->data[i + 1];
}
printf(" Delete contact successfully !\n");
p->size--;
}
}
The illustration :

Running effect :

Function six :search_contact( Find contacts )
void search_contact(contact* p)// Find contacts
{
assert(p);
char name[NAME_MAX];
printf(" Please enter the name of the person you want to search for :>");
scanf("%s", name);
int pos = locate(name, p);
if (pos == 0)
{
printf(" The contact does not exist !\n");
return;
}
else
{
printf("%10s %10s %10s %20s %20s\n", " full name ", " Age ", " Gender ", " Telephone ", " Address ");
printf("%10s %10d %10s %20s %20s\n", p->data[pos].name, p->data[pos].age,
p->data[pos].sex, p->data[pos].tele, p->data[pos].addr);
}
}
Running effect :

Function seven :multify_contact( Modify designated contact information )
void multify_contact(contact* p)// Modify contact information
{
assert(p);
char name[NAME_MAX];
printf(" Please enter the name of the person you want to modify :>");
scanf("%s", name);
int pos = locate(name, p);
if (pos == 0)
{
printf(" The contact does not exist !\n");
return;
}
else
{
printf(" Please enter the modified name :>");
scanf("%s", p->data[pos].name);
printf(" Please enter the modified age :>");
scanf("%d", &(p->data[pos].age));
printf(" Please enter the modified gender :>");
scanf("%s", p->data[pos].sex);
printf(" Please input the modified phone number :>");
scanf("%s", p->data[pos].tele);
printf(" Please enter the modified address :>");
scanf("%s", p->data[pos].addr);
printf(" Modification successful !\n");
}
}
Running effect :

Function eight :show_contact( Show all contact information in the address book )
void show_contact(contact* p)// Show address book information
{
assert(p);
printf("%10s %10s %10s %20s %20s\n", " full name ", " Age ", " Gender ", " Telephone ", " Address ");
for (int i = 0; i < p->size; i++)
{
printf("%10s %10d %10s %20s %20s\n", p->data[i].name, p->data[i].age,
p->data[i].sex, p->data[i].tele, p->data[i].addr);
}
}
The operation effect has been shown in the operation effect of the previous function , We won't show it alone here !
Function nine :sort_contact( Sort contacts )
void sort_contact(contact* p)
{
// Sort contacts by initials
assert(p);
int flag = 1;
PeoInfo temp = {
0 };
for (int i = p->size; i > 0 && flag; i--)
{
flag = 0;
for (int j = 1; j < p->size; j++)
{
if (strcmp(p->data[j].name, p->data[j - 1].name) < 0)
{
temp = p->data[j];
p->data[j] = p->data[j - 1];
p->data[j - 1] = temp;
flag = 1;
}
}
}
printf(" Sort success !\n");
}
Be careful , The so-called sorting refers to sorting by the first letter of the name , Little friends can also make some changes to achieve the sorting effect they want

These lines of English speak strcmp The meaning of the returned value , In the code above , Return value less than 0, It means that the initials of the two names are in the opposite order of the location of the address book
Running effect :

Function ten :save_contact( Save the address book information to a file )
void save_contact(contact* p)// Save the input information to a file
{
assert(p);
FILE* pf = fopen("contact.dat", "w");
if (pf == NULL)
{
printf(" Save failed !\n");
return;
}
else
{
for (int i = 0; i < p->size; i++)
{
// Write the contact information to the file in turn
fwrite(&(p->data[i]), sizeof(PeoInfo), 1, pf);
}
printf(" Saved successfully !\n");
fclose(pf);
pf = NULL;
}
}
When you run the program , Under the same path of this project, a contact.dat file , The contact information you have entered is saved in it
Running effect :



Function 11 :load_contact( Load the information saved in the file , Convenient for next use )
void load_contact(contact* p)// Load the information in the file
{
assert(p);
FILE* pf = fopen("contact.dat", "r");
if (pf == NULL)
{
printf(" Loading failed !\n");
return;
}
else
{
while (fread(&(p->data[p->size]), sizeof(PeoInfo), 1, pf))
{
if (check_contact(p))
{
p->size++;
}
}
printf(" Loading successful !\n");
fclose(pf);
pf = NULL;
}
}
Running effect :

Function 12 :empty_contact( Clear all the contents of the address book )
void empty_contact(contact* p)// Clear address book
{
assert(p);
if (p->size == 0)
{
printf(" Address book is empty !\n");
return;
}
else
{
free(p->data);
p->data = NULL;
p->capacity = 0;
p->size = 0;
printf(" Empty successfully !\n");
}
}
Running effect :

Function 13 :end_contact( Exit procedure )
void end_contact(contact* p)// Exit procedure
{
// Free up used space
assert(p);
free(p->data);
p->data = NULL;
p->capacity = 0;
p->size = 0;
exit(0);
}
because 0 Exit the program directly , So you don't have to show the operation effect
3、 ... and 、 Three documents involved in the project
A project usually uses three files ---- One .h File is used to declare functions, define macros and cover header files
One .c File is used to implement various functions
the other one .c File is used to test the code contained in the first two files

Don't forget to be in .c The document contains .h file
Four 、 Code display
contact.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define NAME_MAX 20
#define SEX_MAX 4
#define TEL_MAX 14
#define ADDR_MAX 30
#define CAPACITY 3
#define ZENG 2
typedef struct PeoInfo
{
// Create contact information structure
char name[NAME_MAX];
char tele[TEL_MAX];
char addr[ADDR_MAX];
char sex[SEX_MAX];
int age;
}PeoInfo;
typedef struct
{
// The address of the contact information structure and the capacity of the address book 、 The current number of contacts is stored in the structure
PeoInfo* data;
int capacity;
int size;
}contact;
void add_contact(contact* p);
int check_contact(contact* p);
void dele_contact(contact* p);
void search_contact(contact* p);
int locate(char name, contact* p);
void multify_contact(contact* p);
void show_contact(contact* p);
void end_contact(contact* p);
void load_contact(contact* p);
void save_contact(contact* p);
void empty_contact(contact* p);
void sort_contact(contact* p);
void init_contact(contact* p);
contact.c
#define _CRT_SECURE_NO_WARNINGS
#include "contact.h"
void init_contact(contact* p)
{
assert(p);// Assertion ,p Not null pointer
p->data = (PeoInfo*)malloc(sizeof(PeoInfo) * CAPACITY);// Open up three structure size spaces for the address book
if (p == NULL)
{
printf(" initialization failed \n");
return;
}
p->size = 0;
p->capacity = CAPACITY;
}
void add_contact(contact* p)// Add a Contact
{
assert(p);
if (check_contact(p) == 0)
{
// Judge whether the capacity increase fails when the address book is full
printf(" The address book is full , Capacity increase failed \n");
return;
}
printf(" Please enter a name :>");
scanf("%s", p->data[p->size].name);
printf(" Please enter age :>");
scanf("%d", &p->data[p->size].age);
printf(" Please enter gender :>");
scanf("%s", p->data[p->size].sex);
printf(" Please input the phone number :>");
scanf("%s", p->data[p->size].tele);
printf(" Please enter the address :>");
scanf("%s", p->data[p->size].addr);
printf(" Add success \n");
p->size++;
}
int check_contact(contact* p)// Check that the address book is full , If it is full, increase the capacity
{
assert(p);
if (p->size == p->capacity)
{
printf(" The address book is full , Increase capacity \n");
// Add two new contact information space at a time
PeoInfo* tmp = (contact*)realloc(p->data, (p->size + ZENG) * sizeof(PeoInfo));
if (tmp == NULL)
{
printf(" Capacity increase failed \n");
return 0;
}
p->data = tmp;
p->capacity += ZENG;
return 1;
}
}
void dele_contact(contact* p)// Delete Contact
{
assert(p);
char name[NAME_MAX];
printf(" Please enter the name of the person you want to delete :>");
scanf("%s", name);
int pos = locate(name, p);
if (pos == -1)
{
printf(" The contact does not exist !\n");
return;
}
else
{
// Move the contact position behind the contact to be deleted forward in turn , Overwrite this contact
for (int i = pos; i < p->size; i++)
{
p->data[i] = p->data[i + 1];
}
printf(" Delete contact successfully !\n");
p->size--;
}
}
void search_contact(contact* p)// Find contacts
{
assert(p);
char name[NAME_MAX];
printf(" Please enter the name of the person you want to search for :>");
scanf("%s", name);
int pos = locate(name, p);
if (pos == -1)
{
printf(" The contact does not exist !\n");
return;
}
else
{
printf("%10s %10s %10s %20s %20s\n", " full name ", " Age ", " Gender ", " Telephone ", " Address ");
printf("%10s %10d %10s %20s %20s\n", p->data[pos].name, p->data[pos].age,
p->data[pos].sex, p->data[pos].tele, p->data[pos].addr);
}
}
int locate(char* name,contact* p)// Find the position of the contact to be operated in the structure array
{
assert(p);
int i = 0;
for (i = 0; i < p->size; i++)
{
if ((strcmp(name, p->data[i].name)) == 0)
{
return i;
}
}
if (i == p->size)
{
return -1;
}
}
void multify_contact(contact* p)// Modify contact information
{
assert(p);
char name[NAME_MAX];
printf(" Please enter the name of the person you want to modify :>");
scanf("%s", name);
int pos = locate(name, p);
if (pos == -1)
{
printf(" The contact does not exist !\n");
return;
}
else
{
printf(" Please enter the modified name :>");
scanf("%s", p->data[pos].name);
printf(" Please enter the modified age :>");
scanf("%d", &(p->data[pos].age));
printf(" Please enter the modified gender :>");
scanf("%s", p->data[pos].sex);
printf(" Please input the modified phone number :>");
scanf("%s", p->data[pos].tele);
printf(" Please enter the modified address :>");
scanf("%s", p->data[pos].addr);
printf(" Modification successful !\n");
}
}
void show_contact(contact* p)// Show address book information
{
assert(p);
printf("%10s %10s %10s %20s %20s\n", " full name ", " Age ", " Gender ", " Telephone ", " Address ");
for (int i = 0; i < p->size; i++)
{
printf("%10s %10d %10s %20s %20s\n", p->data[i].name, p->data[i].age,
p->data[i].sex, p->data[i].tele, p->data[i].addr);
}
}
void end_contact(contact* p)// Exit procedure
{
// Free up used space
assert(p);
free(p->data);
p->data = NULL;
p->capacity = 0;
p->size = 0;
exit(0);
}
void save_contact(contact* p)// Save the input information to a file
{
assert(p);
FILE* pf = fopen("contact.dat", "w");
if (pf == NULL)
{
printf(" Save failed !\n");
return;
}
else
{
for (int i = 0; i < p->size; i++)
{
// Write the contact information to the file in turn
fwrite(&(p->data[i]), sizeof(PeoInfo), 1, pf);
}
printf(" Saved successfully !\n");
fclose(pf);
pf = NULL;
}
}
void load_contact(contact* p)// Load the information in the file
{
assert(p);
FILE* pf = fopen("contact.dat", "r");
if (pf == NULL)
{
printf(" Loading failed !\n");
return;
}
else
{
while (fread(&(p->data[p->size]), sizeof(PeoInfo), 1, pf))
{
if (check_contact(p))
{
p->size++;
}
}
printf(" Loading successful !\n");
fclose(pf);
pf = NULL;
}
}
void empty_contact(contact* p)// Clear address book
{
assert(p);
if (p->size == 0)
{
printf(" Address book is empty !\n");
return;
}
else
{
free(p->data);
p->data = NULL;
p->capacity = 0;
p->size = 0;
printf(" Empty successfully !\n");
}
}
void sort_contact(contact* p)
{
// Sort contacts by initials
assert(p);
int flag = 1;
PeoInfo temp = {
0 };
for (int i = p->size; i > 0 && flag; i--)
{
flag = 0;
for (int j = 1; j < p->size; j++)
{
if (strcmp(p->data[j].name, p->data[j - 1].name) < 0)
{
temp = p->data[j];
p->data[j] = p->data[j - 1];
p->data[j - 1] = temp;
flag = 1;
}
}
}
printf(" Sort success !\n");
}
test.c
#include "contact.h"
void menu()
{
printf("***********************************\n");
printf("****** 0. sign out 1. add to ******\n");
printf("****** 2. Delete 3. lookup ******\n");
printf("****** 4. modify 5. Show ******\n");
printf("****** 6. Sort 7. Empty ******\n");
printf("****** 8. load 9. preservation ******\n");
printf("***********************************\n");
}
void Work()
{
int choice;
contact con;
void(*p[10])(contact* p) =
{
end_contact,
add_contact,
dele_contact,
search_contact,
multify_contact,
show_contact,
sort_contact,
empty_contact,
load_contact,
save_contact
};// Define an array of function pointers , Reduce code redundancy
init_contact(&con);
do
{
menu();
printf(" Please select action :>");
scanf("%d", &choice);
if (choice >= 0 && choice <= 9)
{
// Call the corresponding function according to the input number
(*p[choice])(&con);
}
else
{
printf(" Wrong choice !\n");
return;
}
} while (choice>=0);
}
int main()
{
Work();
return 0;
}
The function pointer array is used in the last file
In fact, the address of each function is treated as an element , Find it through the pointer , Carry out the corresponding operation
5、 ... and 、 summary
Write a blog about small projects for the first time , If there is a mistake , Please don't hesitate to give me some advice , I actively correct
All the above codes use dynamic memory management , File operations , Pointer and other key contents , Hopefully that helped !!!
well , See you next time 
版权声明
本文为[Want to make money]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211132050340.html
边栏推荐
- 机器学习-Sklearn-13(回归类大家族-下——非线性问题:多项式回归(多项式变换后形成新特征矩阵))
- 【软件测试系列十一】《压力测试场景及测试用例模板》
- ASM插桩之美
- Title record of TIANTI competition (II)
- Reverse crawler 30 verification code of a fourth generation slider
- [BSidesCF 2019]Kookie
- Anchor-free新网络:CenterNet携手CornerNet形成了CenterNet++
- [BSidesCF 2019]Kookie
- 国网上海直流充电桩专利公布:保证安全运行,全流程检测,分级运维
- R语言中实现随机森林建模的包randomForest
猜你喜欢

阿里天池比赛——街景字符编码识别

伯克利、三星|一个快速的训练后变换器修剪框架

每日AI前沿术语:主动学习(Active Learning)

新技术又来了,拥抱AGP7.0,准备好告别Transform了吗?

SKU中的销售属性值必须成对填写,那这是什么原因

hiredis和rapidjson库的使用小结

Game industry case 2: player level

Musk lives in the old Internet age?
![[software testing series I] basic knowledge of software testing](/img/00/c6bb357eedcb5ef232d235010ff749.png)
[software testing series I] basic knowledge of software testing

Study notes of deep learning (6)
随机推荐
import in protocol buffer
Anchor free new network: centernet and cornernet form centernet + +
《深度学习》学习笔记(五)
[BSidesCF 2019]Kookie
vscode 经常弹出:尝试在目标目录创建文件时发生一个错误 重试 跳过这个文件 关闭安装程序
国网上海直流充电桩专利公布:保证安全运行,全流程检测,分级运维
win11的WiFi按钮不见了无法联网
基于C#实现文本读取的7种方式
Aaai2022 | unbiased temporal knowledge reasoning based on probabilistic soft logic
Chris LATTNER, father of llvm: the golden age of compilers
“如何实现集中管理、灵活高效的CI/CD”在线研讨会精彩内容分享
Web--用户注册界面
import in protocol buffer
IPEmotion采集J1939协议信号
【软件测试系列七】《软件测试计划》
hiredis和rapidjson库的使用小结
Aicoco AI frontier promotion (4.21)
Importer dans le tampon du Protocole
Massive data generated 421 million yuan of revenue in 2021, and the gross profit margin of database products increased by 8.78%!
Database, add a field data of another table to another table, and add the data you need when adding at the same time