069.结构体-结构体案例1
#include <iostream> using namespace std; //学生结构体 struct Student { //姓名 string sName; //分数 int score; }; //老师的结构体 struct Teacher { //姓名 string tname; //学生数组 struct Student sArray[5]; }; //给老师和学生赋值的函数 void allocatespace(struct Teacher tArray[], int len) { string nameSeed = "ABCDE"; //给老师开始赋值 for (size_t i = 0; i < len; i++) { tArray[i].tname = "teacher_"; tArray[i].tname += nameSeed[i]; //通过循环给每名老师所带的学生赋值 for (size_t 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].score = random; } } } //打印所以信息 void printinfo(Teacher tArray[], int len) { for (size_t i = 0; i < len; i++) { cout << "老师姓名:" << tArray[i].tname << endl; for (size_t j = 0; j < 5; j++) { cout << "\t学生姓名:" << tArray[i].sArray[j].sName << " 考试得分:" << tArray[i].sArray[j].score << endl; } } } int main() { //随机数种子 srand((unsigned int)time(NULL)); //1.创建3名老师的数组 struct Teacher tArray[3]; //2.通过函数给3名老师的信息赋值,并给老师带的学生信息赋值 int len = sizeof(tArray) / sizeof(tArray[0]); allocatespace(tArray, len); //3.打印所有老师和学生信息 printinfo(tArray, len); system("pause"); return 0; }