简单的图书管理系统

要求:

定义一个结构体,存储图书的信息,包括名字、价格和数量

使用结构体数组,数组容量未知 ,存储5本书的信息在数组中

写四个函数
1. 统计有效图书数量
2. 将所有有效图书信息打印出来
3. 在某个位置插入一本书的信息
4. 在某个位置删除一本书的信息
考虑:数组在内存中是连续的,当插入信息时,插入位置后的图书信息对应下标都要 + 1;当删除信息时,删除位置后的图书信息对应下标都要 - 1

代码:

#include<stdio.h>
#include<stdlib.h>

struct  book
{
	char name[20] ;
	int number;
	float pc;
};

int size(const struct  book* stu)//统计图书数量
{
	int n = 0;
	while (stu->number != 0)
	{
		n++;
		stu++;
	}
	return n;
}

void sum(const struct  book *stu,int n)//输出图书信息
{
	for (int i = 0; i < n; i++)
	{
		printf("第%d本书的名字,数量和价格:%s,%d,%g\n", i + 1, stu[i].name, stu[i].number, stu[i].pc);
	}
}

void insert(struct  book* stu, struct  book* stu_info, int location,int* n)//插入图书
{
	struct  book* p = stu;//定义一个变量存放数组的首地址
	p += location;//直接定位到需要插入的位置
	struct  book* p_i= (struct  book*)malloc(sizeof(struct  book));//定义一个结点来存放需要插入的图书信息
	/*memset(stu_info, 0, sizeof(struct  book));*///error 不能将p_i初始化
	*n += 1;//长度加一
	while (p < stu + *n)
	{
		*p_i = *p; //先保留现在位置的数据
		*p = *stu_info;//将现在位置的数据替换成要插入的信息
		*stu_info = *p_i;//把现在的信息作为下一个要插入的信息
		p++;
	}
	free(p_i);
	p_i = NULL;
}

void delete(struct book* stu, int location, int *n)//删除图书
{
	struct book* stu_delete = stu;
	stu_delete += location;
	*n -= 1;
	while (stu_delete < stu + *n)
	{
		*stu_delete = *(stu_delete + 1);//把下一个数据给当前
		stu_delete++;
	}
	memset(stu+*n,0,sizeof(struct book));//清空多余项
}


int main()
{
	struct  book* stu = (struct  book*)malloc(sizeof(struct  book) * 10);//动态分配内存
	memset(stu, 0, sizeof(struct  book) * 10);//初始化
	//struct  book stu[10] = {0};
	int i = 0;
	do
	{
		printf("输入第%d本书的名字,数量和价格:", i+ 1);
		scanf("%s%d%f", &stu[i].name, &stu[i].number, &stu[i].pc);
		i++;
	} while (i < 5);
	//int i = 5;
	//for (int x =0 ;x<i;x++)//输入信息
	//{
	//	printf("输入第%d本书的名字,数量和价格:",x+1);
	//	scanf("%s%d%f",&stu[x].name, &stu[x].number, &stu[x].pc);
	//}
	printf("\n");

	int n = size(stu);
	printf("有效书籍数量为%d\n", n);
	printf("\n");
	sum(stu, n);//输出信息
	printf("\n");
	struct  book* stu_info = (struct  book*)malloc(sizeof(struct  book));//定义插入的图书信息
	memset(stu_info, 0, sizeof(struct  book));

	printf("请输入要插入图书的信息:");
	scanf("%s%d%f", &stu_info->name, &stu_info->number, &stu_info->pc);

	int location = 0;
	printf("请输入要插入图书的位置:");
	scanf("%d", &location);
	printf("\n");
	insert(stu,stu_info, location, &n);
	sum(stu, n);//输出信息

	printf("请输入要删除图书的位置:");
	scanf("%d", &location);
	printf("\n");
	delete(stu, location, &n);
	sum(stu, n);//输出信息

	free(stu);
	free(stu_info);
	stu = NULL;
	stu_info = NULL;
	return 0;
}


效果图:

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值