案例要求:定义一个教师结构体数组,每个教师带五个学生,所以教师数组嵌套学生数组。
#include <iostream>
#include<string>
#include<ctime>
using namespace std;
struct student {
string name;
int score=0;
};
struct teacher {
student stu[5];
string name;
};
void fuzhi(struct teacher tea[], int len) {
string name_seed = "ABCDE";
srand((unsigned int)time(NULL));
for (int i = 0; i < 3; i++) {
tea[i].name = "teacher_";
tea[i].name += name_seed[i];
for (int j = 0; j < 5; j++) {
tea[i].stu[j].name = "student_";
tea[i].stu[j].name += name_seed[j];
int random = rand() % 61 + 40;
tea[i].stu[j].score = random;
}
}
}
void show(teacher tea[], int len) {
for (int i = 0; i < 3; i++) {
cout << tea[i].name << endl;
for (int j = 0; j < len; j++) {
cout << tea[i].stu[j].name << " ";
cout << tea[i].stu[j].score << " " << endl;
}
cout << " " << endl;
}
}
int main()
{
teacher tea[3];
int len = sizeof(tea[0].stu) / sizeof(tea[0].stu[0]);
fuzhi(tea, len);
show(tea, len);
}