问题描述:学校正在做毕设,每名老师带领5个学生,共3名老师,设计老师和学生的结构体, 在老师的结构体中包含老师的姓名和存放5个学生的数组作为成员,学生的成员有姓名和考试分数,创建数组存放三名老师,通过函数给每个老师及所带的学生赋值。最终打印老师数据以及老师所带学生数据。
定义学生结构体
struct Student//学生结构体的定义
{
string sname;//学生名字
int score;//学生分数
};
定义老师结构体
struct Teacher //老师结构体定义
{
string tname;//老师的名字
struct Student sArray[5];//学生数组
};
创建函数给老师及老师所带学生信息赋值
//创建函数给老师和学生赋值
void allocateSpace(struct Teacher tArray[], int len)
{
srand((unsigned int)time(NULL));
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 Score = rand() % 61 + 40;
tArray[i].sArray[j].score = Score;
}
}
创建函数打印老师及所带学生信息
//创建函数打印老师和所带学生信息
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 <<
" 考试分数: " << tArray[i].sArray[j].score << endl;
}
}
}
Main函数
int main()
{
//1、创建三名老师的数组
struct Teacher tArray[3];
//2、通过函数给3名老师的信息赋值,以及给老师所带学生的信息赋值
int len = sizeof(tArray) / sizeof(tArray[0]);
allocateSpace(tArray, len);
//3、通过函数打印所有老师以及所带学生的信息
printInfo(tArray,len);
system("pause");
return 0;
}
总结
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
//结构体的嵌套
struct Student//学生结构体的定义
{
string sname;//学生名字
int score;//学生分数
};
struct Teacher //老师结构体定义
{
string tname;//老师的名字
struct Student sArray[5];//学生数组
};
//创建函数给老师和学生赋值
void allocateSpace(struct Teacher tArray[], int len)
{
srand((unsigned int)time(NULL));
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 Score = rand() % 61 + 40;
tArray[i].sArray[j].score = Score;
}
}
}
//创建函数打印老师和所带学生信息
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 <<
" 考试分数: " << tArray[i].sArray[j].score << endl;
}
}
}
int main()
{
//1、创建三名老师的数组
struct Teacher tArray[3];
//2、通过函数给3名老师的信息赋值,以及给老师所带学生的信息赋值
int len = sizeof(tArray) / sizeof(tArray[0]);
allocateSpace(tArray, len);
//3、通过函数打印所有老师以及所带学生的信息
printInfo(tArray,len);
system("pause");
return 0;
}