4.结构体案例1

2020-12-29  本文已影响0人  lxr_

#include<iostream>

#include<string>

#include<ctime>

using namespace std;

struct Student

{

    string sName;

    int age;

};

struct  Teacher

{

    string tName;

    Student sArray[5];

};

void allocateSpace(Teacher tArray[],int len)//初始化结构体数组

{

    string nameSeed = "abcde";

    for (int i = 0; i < len; i++)

    {

        tArray[i].tName = "teacher_";

        tArray[i].tName += nameSeed[i];

        for (int j = 0; j < 5; j++)

        {

            tArray[i].sArray[j].sName = "student_" ;

            tArray[i].sArray[j].sName += nameSeed[j];

            tArray[i].sArray[j].age = rand()%31 +20;

        }

    }

}

void printInfo(Teacher tArray[],int len)

{

    for (int i = 0; i < len; i++)

    {

        cout << "老师姓名:" << tArray[i].tName << endl;

        for (int j = 0; j < 5; j++)

        {

            cout << "学生:" << tArray[i].sArray[j].sName;

            cout << "年龄:"<<tArray[i].sArray[j].age << endl;

        }

    }

}

int main()

{

    srand((unsigned int)time(NULL));//随机数种子

    Teacher tArray[3];

    int len = sizeof(tArray) / sizeof(tArray[0]);

    allocateSpace(tArray, len);

    printInfo(tArray, len);

    system("pause");

    return 0;

}

上一篇 下一篇

猜你喜欢

热点阅读