案例描述:
学校在做毕设项目,共三名老师,规定每名老师带5个学生。
设计老师和学生的结构体,在老师的结构体中包括老师姓名和学生的数组作为成员。学生结构体中包括学生姓名和分数。
通过函数给老师和所带学生赋值,并打印出相关信息。
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
//学生的结构体定义
struct student
{
string sName;
int sScore;
};
//老师的结构体定义
struct teacher
{
string tName;
//学生数组
struct student sArray[5];
};
//给老师和学生信息赋值的函数
void allocateSpace(struct teacher tArray[],int len)
{
string nameSeed="ABCDE";
//给老师赋值
for(int i=0;i<len;i++)
{
tArray[i].tName="Teacher_";
tArray[i].tName+=nameSeed[i];
//给学生赋值
for(int j=0;j<5;j++)
{
tArray[i].sArray[j].sName="Student_";
tArray[i].sArray[j].sName+=nameSeed[j];
//给学生随机分数
int random=rand()%61+40;
tArray[i].sArray[j].sScore=random;
}
}
}
//打印所有老师的信息的函数
void printInfo(struct teacher tArray[],int len)
{
for(int i=0;i<len;i++)
{
cout<<"老师姓名:"<<tArray[i].tName<<endl;
for(int j=0;j<5;j++)
{
cout<<"\t学生姓名:"<<tArray[i].sArray[j].sName<<"\t学生成绩:"<<tArray[i].sArray[j].sScore<<endl;
}
}
}
int main()
{
srand ((unsigned int)time(NULL));
//创建3名老师的数组
struct teacher tArray[3];
//计算老师数组长度
int len =sizeof(tArray) / sizeof(tArray[0]);
//通过函数给老师和学生信息赋值
allocateSpace(tArray,len);
//通过函数打印所有老师的信息
printInfo(tArray,len);
return 0;
}