6.7重学C++之【结构体-案例#1】

#include<iostream>
#include<string>
#include<stdlib.h>  //随机数用到
#include<ctime>  //时间用到
using namespace std;


/*
    结构体-案例#1
    三个老师,每个老师带五个学生做毕设
*/


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 (int i=0; i<len; i++){
        //tArray[i].tName = "Teacher_" += nameSeed[i]; //报错
        tArray[i].tName = "Teacher_";
        tArray[i].tName += nameSeed[i];
        for (int j=0; j<5; j++){
            //tArray[i].sArray[j].sName = "Student_" += nameSeed[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 << "老师姓名:" << 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(){
    struct teacher tArray[3];
    int len = sizeof(tArray) / sizeof(tArray[0]);

    srand((unsigned int)time(NULL)); // 随机数种子,用于随机性分数赋值
    allocateSpace(tArray, len);

    printInfo(tArray, len);

    return 0;
}

posted @ 2021-03-11 12:05  yub4by  阅读(35)  评论(0编辑  收藏  举报