案例描述: 学校在准备做毕设项目,每名老师带5名学生,共有3名老师。 需求如下: 设计学生和老师的结构体,其中在老师的结构体中,有老师姓名和一个存放5名学生的数组作为成员,学生的成员有姓名及分数,创建数组用于存放3名老师,通过函数给每个老师及其所带的学生进行赋值,最终要求打印出老师数据及老师所带学生的详细信息。 思路图
1、构建结构体
struct Student { string sName; int score; }; struct Teacher { string tName; struct Student sArray[5]; };2、通过函数对老师及其所带学生进行赋值处理
//给老师及其所带的学生进行赋值 void nameLocate(struct 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]; int random = rand() % 61 + 40; tArray[i].sArray[j].score = random; } } }3、将信息打印出来
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; } } }4、完整代码:
#include<iostream> #include<string> #include<ctime> using namespace std; struct Student { string sName; int score; }; struct Teacher { string tName; struct Student sArray[5]; }; //给老师及其所带的学生进行赋值 void nameLocate(struct 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]; int random = rand() % 61 + 40; 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() { srand((unsigned int)time(NULL)); //1、首先创建老师的数组 struct Teacher tArray[3]; //2、对每个老师所带的学生进行赋值 int len = sizeof(tArray) / sizeof(tArray[0]); nameLocate(tArray, len); //3、打印 printInfo(tArray, len); system("pause"); return 0; }5、实现效果 6、补充说明 (1)程序通过随机种子使得产生随机数成为学生的成绩,主要的代码体现如下:
int random = rand() % 61 + 40; tArray[i].sArray[j].score = random; srand((unsigned int)time(NULL));(2)数组的长度获取,可通过下面的方式以实现长度自由。
int len = sizeof(tArray) / sizeof(tArray[0]);