题意:有3名老师,含关键字姓名和学生。每位老师带5名学生,含姓名和分数。使用结构体表示,并打印出信息。
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
//定义学生结构体
struct Student {
string sname;
int score;
};
struct Teacher {
string name;
struct Student sArray[5];
};
//给老师和学生赋值的函数
void allocateSpace(struct Teacher tArray[], int len)
{
string nameSeed = "ABCDE";
for (int i = 0; i < len; i++)
{
tArray[i].name = "Teacher_";
tArray[i].name += 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;//随机数,40-100分之间
tArray[i].sArray[j].score = random;
}
}
}
void PrintInfo(struct Teacher tArray[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "Teach name:" << tArray[i].name << endl;
for (int j = 0; j < 5; j++)
{
cout << "\tStu name:" << tArray[i].sArray[j].sname << " Score:" << tArray[i].sArray[j].score << 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);
system("pause");
return 0;
}
输出结果: