1. #include <iostream>
    2. #include <string>
    3. #include <ctime>
    4. using namespace std;
    5. // 定义学生结构体
    6. struct Student {
    7. string name;
    8. int age;
    9. int score;
    10. };
    11. // 定义老师结构体
    12. struct Teacher {
    13. string name;
    14. struct Student stds[5];
    15. };
    16. void allocateSpace(struct Teacher teacherArray[], int len);
    17. void printAllInfo(struct Teacher teacherArray[], int len);
    18. int main() {
    19. // 随机数种子
    20. srand((unsigned int) time(NULL));
    21. // 1.创建3名老师的数组
    22. struct Teacher teacherArray[3];
    23. int len = sizeof(teacherArray) / sizeof(teacherArray[0]);
    24. // 2.通过函数给3名老师的信息赋值,并且给老师带的学生信息也赋值
    25. allocateSpace(teacherArray, len);
    26. // 3.打印所有老师及所带的学生信息
    27. printAllInfo(teacherArray, len);
    28. return 0;
    29. }
    30. void allocateSpace(struct Teacher teacherArray[], int len) {
    31. for (int i = 0; i < len; i++) {
    32. teacherArray[i].name = "teacher_";
    33. teacherArray[i].name += i;
    34. for (int j = 0; j < 5; j++) {
    35. teacherArray[i].stds[j].name = "student_" + i;
    36. teacherArray[i].stds[j].age = 10 + i;
    37. int s = rand() % 61 + 40;
    38. teacherArray[i].stds[j].score = s;
    39. }
    40. }
    41. }
    42. void printAllInfo(struct Teacher teacherArray[], int len) {
    43. for (int i = 0; i < len; i++) {
    44. cout << "teacher :" << teacherArray[i].name << endl;
    45. for (int j = 0; j < 5; j++) {
    46. cout << "\tstudent name :" << "teacher_" << teacherArray[i].name << teacherArray[i].stds[j].name << endl;
    47. cout << "\tstudent age :" << "teacher_" << teacherArray[i].name << teacherArray[i].stds[j].age << endl;
    48. cout << "\tstudent score :" << "teacher_" << teacherArray[i].name << teacherArray[i].stds[j].score << endl;
    49. }
    50. }
    51. }