C++基础总结 结构题解

Computer science should be called computing science, for the same reason why surgery is not called knife science.

- E. Dijkstra

这是C++基础学习的最后一道总结题,以后便开始更新介绍C++面向对象编程和数据结构与算法的题解以及计算机操作系统。在此向学习C++的同学们推荐一本书《C++ primer plus》第六版,这本书十分适合像我一样跨考的人读,讲解的非常详细,但是过于详细,所以需要同学们过滤自己不需要的信息。

案例描述:

学校正在做毕设项目,每名老师带领5个学生,总共有3名老师,需求如下

设计学生和老师的结构体,其中在老师的结构体中,有老师姓名和一个存放5名学生的数组作为成员

学生的成员有姓名、考试分数,创建数组存放3名老师,通过函数给每个老师及所带的学生赋值

最终打印出老师数据以及老师所带的学生数据。

#include<iostream>
#include<string>
#include<ctime>
using mamespace std;

struct Student
{
	string name;
	int score;
};
struct Teacher
{
	string name;
	Student sArray[5];  // 结构的嵌套
};

void allocateSpace(Teacher tArray[] , int len)  //地址传递,形参可以修改实参  
{
	string tName = "教师";
	string sName = "学生";
	string nameSeed = "ABCDE";
	for (int i = 0; i < len; i++)
	{ 
		tArray[i].name = tName + nameSeed[i]; // “教师”后追加seed来区分 
		
		for (int j = 0; j < 5; j++)
		{
			tArray[i].sArray[j].name = sName + nameSeed[j];
			tArray[i].sArray[j].score = rand() % 61 + 40;   //利用随机函数调整分数
		}
	}
}

void printTeachers(Teacher tArray[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << tArray[i].name << endl;
		for (int j = 0; j < 5; j++)
		{
			cout << "\t姓名:" << tArray[i].sArray[j].name << " 分数:" << tArray[i].sArray[j].score << endl;
		}
	}
}

int main() {

	srand((unsigned int)time(NULL)); //随机数种子 头文件 #include <ctime>

	Teacher tArray[3]; //老师数组

	int len = sizeof(tArray) / sizeof(Teacher);

	allocateSpace(tArray, len); //创建数据

	printTeachers(tArray, len); //打印数据
	
	system("pause");

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值