当前位置:网站首页>Dynamic address book
Dynamic address book
2022-07-04 09:47:00 【skeet follower】
Catalog
One . Preparation of address book
Two . Implementation steps of address book
Store personal information ( static state )
Store personal information ( dynamic )
Destroy the address book ( dynamic )
3、 ... and . Source code ( dynamic )
One . Preparation of address book
First of all, we need to think about what we need to do to open up an address book . Keep some basic information about people ( name + Gender + Age + Telephone + address ), Add contacts , Delete Contact , Modify contact , Find contacts , Finally, save the document so that it cannot be found .
Here we have created three files , The first header file is "contact.h" Declaration for function , Definition of global variables ; The second is “contact.c" Used to implement the functions declared in the header file ; The third is "test.c" Used to test functions .
Now we will discuss and study with you one by one :
Two . Implementation steps of address book
Create main menu
stay “test.c" In the definition of menu() Function to create the main menu , Then the user makes a selection , use do..while Cycle through , Defining variables input Enter data , Reuse switch Function to operate. Enumeration is used here to make it clearer . The code is as follows :
void menu()
{
printf("******************************\n");
printf("**** 1. add 2. del *****\n");
printf("**** 3. search 4. modify****\n");
printf("**** 5. show 0. exit ***\n");
printf("******************************\n");
}
enum Option {
EXIT,
ADD,
DEL,
SEARCH,
MODIFY,
SHOW
};
int main()
{
int input = 0;
do {
menu();
printf(" Please enter your choice :");
scanf("%d", &input);
switch (input) {
case ADD:
break;
case DEL:
break;
case SEARCH:
break;
case MODIFY:
break;
case SHOW:
break;
case EXIT:
printf(" Exit address book \n");
break;
default:
printf(" Wrong choice \n");
break;
}
} while (input);
return 0;
}
Store personal information ( static state )
We assume to store 1000 Human information , The information includes : name + Gender + Age + Telephone + address ;
stay "contact.h" in , The code is as follows :
/ Describe personal information
struct PeoInfo {
char name[30];
int age;
char sex[5];
char tele[12];
char addr[30];
};
// Mail list
struct Contact {
struct PeoInfo data[1000];//1000 Personal data is stored in data Array ;
int sz;// Record the number of valid information in the current address book ;
};
But you will find it troublesome if you need to change the size of the name or address array , Here we quote define Preprocessing command , Define the macro , The code is as follows :
#define NAME_MAX 30
#define SEX_MAX 5
#define TELE_MAX 12
#define ADDR_MAX 30
#define MAX 1000
// Describe personal information
struct PeoInfo {
char name[NAME_MAX];
int age;
char sex[SEX_MAX];
char tele[TELE_MAX];
char addr[ADDR_MAX];
};
// Mail list
struct Contact {
struct PeoInfo data[MAX];//1000 Personal data is stored in data Array ;
int sz;// Record the number of valid information in the current address book ;
};
Next, you need to initialize , take sz and data All initialized to 0, No information by default . stay "contact.c" in , The code is as follows :
void InitContact(struct Contact* pc)
{
pc->sz = 0;// No information by default
memset(pc->data, 0, sizeof(pc->data));// take data The data in the array is initialized to 0
}
It will obviously be much more convenient after such modification , But there is something wrong , Here we define data Arrays can hold 1000 Personal data , Suppose we only store 3 Personal information , This will waste a lot of space , Some people say we can change it to 4, But every time we have to modify it in real time according to the number of storage data The data stored in the array is troublesome , So we thought of opening up a dynamic space , First, let's give data Array 3 Storage space , Use when space is insufficient realloc Function for each 2 individual 2 The opening of a space , This will not cause a waste of space , And it's easy to operate .
Store personal information ( dynamic )
The revised code is as follows :
#define DEFAULT_SZ 3
#define NAME_MAX 30
#define SEX_MAX 5
#define TELE_MAX 12
#define ADDR_MAX 30
//#define MAX 1000
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// Describe personal information
struct PeoInfo {
char name[NAME_MAX];
int age;
char sex[SEX_MAX];
char tele[TELE_MAX];
char addr[ADDR_MAX];
};
// Mail list
struct Contact {
struct PeoInfo* data;//1000 Personal data is stored in data Array ;
int sz;// Record the number of valid information in the current address book ;
int capcity;// The maximum capacity of the current address book ;
};
initialization :
void InitContact(struct Contact* pc)
{
/*pc->sz = 0;
memset(pc->data, 0, sizeof(pc->data));*/
pc->data = (struct PeoInfo*)malloc(DEFAULT_SZ * sizeof(struct PeoInfo));
pc->sz = 0;
pc->capcity = DEFAULT_SZ;
}
Add contacts ( static state )
To add contacts, first judge whether the storage space is full , If it is not full, continue to enter the new name + Age + Gender + Telephone + Address ; stay ”contact.c" The code in is as follows :
void AddContact(struct Contact* pc) {
if (pc->sz == MAX) {
printf(" The address book is full \n");
}
else {
printf(" Please enter a name :>");
scanf("%s", pc->data[pc->sz].name);
printf(" Please enter age :>");
scanf("%d", &(pc->data[pc->sz].age));
printf(" Please enter gender :>");
scanf("%s", pc->data[pc->sz].sex);
printf(" Please input the phone number :>");
scanf("%s", pc->data[pc->sz].tele);
printf(" Please enter the address :>");
scanf("%s", pc->data[pc->sz].addr);
printf(" Add success \n");
pc->sz++;
}
}
Add contacts ( dynamic )
You need to create a new CheckCapacity() To check the capacity of the current address book , If the full , Just add space , If not , Do nothing .
void CheckCapacity(struct Contact* pc) {
if (pc->sz == pc->capacity) {
// increase capacity
struct PeoInfo* ptr = realloc(pc->data, (pc->capacity + 2) * sizeof(struct PeoInfo));
if (ptr != NULL) {
pc->data = ptr;
pc->capacity += 2;
printf(" Successful expansion \n");
}
else {
printf(" Capacity increase failed \n");
}
}
}
void AddContact(struct Contact* pc)
{
// Check the capacity of the current address book
//1. If the full , Just add space
//2. If not , Don't do anything
CheckCapacity(pc);
printf(" Please enter a name :>");
scanf("%s", pc->data[pc->sz].name);
printf(" Please enter age :>");
scanf("%d", &(pc->data[pc->sz].age));
printf(" Please enter gender :>");
scanf("%s", pc->data[pc->sz].sex);
printf(" Please input the phone number :>");
scanf("%s", pc->data[pc->sz].tele);
printf(" Please enter the address :>");
scanf("%s", pc->data[pc->sz].addr);
printf(" Add success \n");
pc->sz++;
}
Show contacts
The code is as follows :
void ShowContact(struct Contact* pc)
{
int i = 0;
// title
printf("%15s\t%5s\t%8s\t%15s\t%30s\n\n", "name", "age", "sex", "tele", "addr");
for (i = 0; i < pc->sz; i++)
{
// Print every data
printf("%15s\t%5d\t%8s\t%15s\t%30s\n",
pc->data[i].name,
pc->data[i].age,
pc->data[i].sex,
pc->data[i].tele,
pc->data[i].addr);
}
}
Next, we will test the content compiled above :
Delete the specified contact
Through analysis, it will be found that , lookup , When modifying contacts, you need to compare the entered name with the name saved in the address book one by one to see whether it is the same , For convenience, we define a FindName() Functions make code simpler . To delete a contact, we only need to overwrite the following data one by one with the previous data until the specified contact , use for The loop is done .
The code is as follows :
int FindName(struct Contact* pc, char name[NAME_MAX])
{
int i = 0;
for (i = 0; i < pc->sz; i++) {
if (strcmp(pc->data[i].name, name) == 0) {
return i;
}
}
return -1;
}
void DelContact(struct Contact* pc)
{
char name[NAME_MAX];
int pos = 0;
printf(" Please enter the name of the person you want to delete :>");
scanf("%s", &name);
pos = FindName(pc, name);
if (pos == -1) {
printf(" The deleted person does not exist \n");
}
else {
int j = 0;
for (j = pos; j < pc->sz - 1; j++) {
pc->data[j] = pc->data[j + 1];
}
pc->sz--;
printf(" Delete successful \n");
}
}
Find the designated contact
void SearchContact(struct Contact* pc) {
char name[NAME_MAX];
int pos = 0;
printf(" Please enter the name of the person you want to search for :>");
scanf("%s", name);
pos = FindName(pc, name);
if (pos == -1) {
printf(" The person you're looking for doesn't exist \n");
}
else {
printf("%15s\t%5s\t%8s\t%15s\t%30s\n\n", "name", "age", "sex", "tele", "addr");
// Print every data
printf("%15s\t%5d\t%8s\t%15s\t%30s\n",
pc->data[pos].name,
pc->data[pos].age,
pc->data[pos].sex,
pc->data[pos].tele,
pc->data[pos].addr);
}
}
Modify the specified contact
void ModifyContact(struct Contact* pc)
{
char name[NAME_MAX];
int pos = 0;
printf(" Please enter the name of the person you want to modify \n");
scanf("%s", name);
pos = FindName(pc, name);
if (pos == -1) {
printf(" The information of the person to modify does not exist \n");
}
else {
printf(" Please enter a name :>");
scanf("%s", pc->data[pos].name);
printf(" Please enter age :>");
scanf("%d", &(pc->data[pos].age));
printf(" Please enter gender :>");
scanf("%s", pc->data[pos].sex);
printf(" Please input the phone number :>");
scanf("%s", pc->data[pos].tele);
printf(" Please enter the address :>");
scanf("%s", pc->data[pos].addr);
printf(" Modified to complete \n");
}
}
The static address book is basically over , The dynamic address book needs to be destroyed .
Destroy the address book ( dynamic )
void DestroyContact(struct Contact* pc)
{
free(pc->data);
pc->data = NULL;
}
3、 ... and . Source code ( dynamic )
contact.h
#pragma once
#define DEFAULT_SZ 3
#define NAME_MAX 30
#define SEX_MAX 5
#define TELE_MAX 12
#define ADDR_MAX 30
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// Describe personal information
struct PeoInfo {
char name[NAME_MAX];
int age;
char sex[SEX_MAX];
char tele[TELE_MAX];
char addr[ADDR_MAX];
};
// Mail list
struct Contact {
struct PeoInfo* data;//1000 Personal data is stored in data Array ;
int sz;// Record the number of valid information in the current address book ;
int capcity;// The maximum capacity of the current address book ;
};
// Initialize address book
void InitContact(struct Contact* pc);
// Add contacts
void AddContact(struct Contact* pc);
// Show all contacts
void ShowContact(struct Contact* pc);
// Delete designated contact
void DelContact(struct Contact* pc);
// Find the specified contact
void SearchContact(struct Contact* pc);
// Modify the specified contact
void ModifyContact(struct Contact* pc);
// The destruction
void DestroyContact(struct Contact* pc);
contact.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"contact.h"
void InitContact(struct Contact* pc)
{
pc->data = (struct PeoInfo*)malloc(DEFAULT_SZ * sizeof(struct PeoInfo));
if (pc->data == NULL) {
return 0;
}
pc->sz = 0;
pc->capcity = DEFAULT_SZ;
}
void CheckCapacity(struct Contact* pc) {
if (pc->sz == pc->capcity) {
struct PeoInfo* ptr = realloc(pc->data, (pc->capcity + 2)*sizeof(struct PeoInfo));
if (ptr != NULL) {
pc->data = ptr;
pc->capcity += 2;
printf(" Successful expansion \n");
}
else {
printf(" Capacity increase failed \n");
}
}
}
void AddContact(struct Contact* pc) {
CheckCapacity(pc);
printf(" Please enter a name :>");
scanf("%s", pc->data[pc->sz].name);
printf(" Please enter age :>");
scanf("%d", &(pc->data[pc->sz].age));
printf(" Please enter gender :>");
scanf("%s", pc->data[pc->sz].sex);
printf(" Please input the phone number :>");
scanf("%s", pc->data[pc->sz].tele);
printf(" Please enter the address :>");
scanf("%s", pc->data[pc->sz].addr);
printf(" Add success \n");
pc->sz++;
}
void ShowContact(struct Contact* pc)
{
int i = 0;
// title
printf("%15s\t%5s\t%8s\t%15s\t%30s\n\n", "name", "age", "sex", "tele", "addr");
for (i = 0; i < pc->sz; i++)
{
// Print every data
printf("%15s\t%5d\t%8s\t%15s\t%30s\n",
pc->data[i].name,
pc->data[i].age,
pc->data[i].sex,
pc->data[i].tele,
pc->data[i].addr);
}
}
int FindName(struct Contact* pc, char name[NAME_MAX])
{
int i = 0;
for (i = 0; i < pc->sz; i++) {
if (strcmp(pc->data[i].name, name) == 0) {
return i;
}
}
return -1;
}
void DelContact(struct Contact* pc)
{
char name[NAME_MAX];
int pos = 0;
printf(" Please enter the name of the person you want to delete :>");
scanf("%s", &name);
pos = FindName(pc, name);
if (pos == -1) {
printf(" The deleted person does not exist \n");
}
else {
int j = 0;
for (j = pos; j < pc->sz - 1; j++) {
pc->data[j] = pc->data[j + 1];
}
pc->sz--;
printf(" Delete successful \n");
}
}
void SearchContact(struct Contact* pc) {
char name[NAME_MAX];
int pos = 0;
printf(" Please enter the name of the person you want to search for :>");
scanf("%s", name);
pos = FindName(pc, name);
if (pos == -1) {
printf(" The person you're looking for doesn't exist \n");
}
else {
printf("%15s\t%5s\t%8s\t%15s\t%30s\n\n", "name", "age", "sex", "tele", "addr");
// Print every data
printf("%15s\t%5d\t%8s\t%15s\t%30s\n",
pc->data[pos].name,
pc->data[pos].age,
pc->data[pos].sex,
pc->data[pos].tele,
pc->data[pos].addr);
}
}
void ModifyContact(struct Contact* pc)
{
char name[NAME_MAX];
int pos = 0;
printf(" Please enter the name of the person you want to modify \n");
scanf("%s", name);
pos = FindName(pc, name);
if (pos == -1) {
printf(" The information of the person to modify does not exist \n");
}
else {
printf(" Please enter a name :>");
scanf("%s", pc->data[pos].name);
printf(" Please enter age :>");
scanf("%d", &(pc->data[pos].age));
printf(" Please enter gender :>");
scanf("%s", pc->data[pos].sex);
printf(" Please input the phone number :>");
scanf("%s", pc->data[pos].tele);
printf(" Please enter the address :>");
scanf("%s", pc->data[pos].addr);
printf(" Modified to complete \n");
}
}
void DestroyContact(struct Contact* pc)
{
free(pc->data);
pc->data = NULL;
}
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"contact.h"
void menu()
{
printf("******************************\n");
printf("**** 1. add 2. del *****\n");
printf("**** 3. search 4. modify****\n");
printf("**** 5. show 0. exit ***\n");
printf("******************************\n");
}
enum Option {
EXIT,
ADD,
DEL,
SEARCH,
MODIFY,
SHOW
};
int main()
{
int input = 0;
// Create address book
struct Contact con;
// Initialize address book
InitContact(&con);
do {
menu();
printf(" Please enter your choice :");
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 EXIT:
// Destroy the address book , Free dynamic memory
DestroyContact(&con);
printf(" Exit address book \n");
break;
default:
printf(" Wrong choice \n");
break;
}
} while (input);
return 0;
}
Want to know how to operate documents , Point a praise , Let's discuss it slowly in the next episode !
边栏推荐
- Launpad | Basics
- Kotlin set operation summary
- Summary of the most comprehensive CTF web question ideas (updating)
- Web端自动化测试失败原因汇总
- Hands on deep learning (44) -- seq2seq principle and Implementation
- Application of safety monitoring in zhizhilu Denggan reservoir area
- Write a jison parser from scratch (2/10): learn the correct posture of the parser generator parser generator
- Hands on deep learning (38) -- realize RNN from scratch
- C # use ffmpeg for audio transcoding
- Hands on deep learning (45) -- bundle search
猜你喜欢
QTreeView+自定义Model实现示例
2022-2028 global protein confectionery industry research and trend analysis report
2022-2028 global special starch industry research and trend analysis report
Summary of reasons for web side automation test failure
Hands on deep learning (41) -- Deep recurrent neural network (deep RNN)
Qtreeview+ custom model implementation example
2022-2028 global strain gauge pressure sensor industry research and trend analysis report
2022-2028 global industrial gasket plate heat exchanger industry research and trend analysis report
百度研发三面惨遭滑铁卢:面试官一套组合拳让我当场懵逼
Hands on deep learning (III) -- Torch Operation (sorting out documents in detail)
随机推荐
Write a jison parser from scratch (4/10): detailed explanation of the syntax format of the jison parser generator
Pcl:: fromrosmsg alarm failed to find match for field 'intensity'
Golang Modules
Rules for using init in golang
Four common methods of copying object attributes (summarize the highest efficiency)
How can Huawei online match improve the success rate of player matching
2022-2028 global industry research and trend analysis report on anterior segment and fundus OTC detectors
PHP personal album management system source code, realizes album classification and album grouping, as well as album image management. The database adopts Mysql to realize the login and registration f
Regular expression (I)
System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
5g/4g wireless networking scheme for brand chain stores
Golang type comparison
Write a jison parser (7/10) from scratch: the iterative development process of the parser generator 'parser generator'
QTreeView+自定义Model实现示例
On Multus CNI
2022-2028 global intelligent interactive tablet industry research and trend analysis report
In the case of easyUI DataGrid paging, click the small triangle icon in the header to reorder all the data in the database
Hands on deep learning (35) -- text preprocessing (NLP)
2022-2028 global seeder industry research and trend analysis report
Kotlin 集合操作汇总