提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
目录
前言
黑马程序员P70 结构体-结构体案例1
学校正在做毕设项目,每名老师带领5个学生,总共有3名老师,需求如下:
1、设计学生和老师的结构体,其中在老师的结构体中,有老师名字和一个存放5名学生的数组作为成员;
2、学生的成员有名字、考试分数、创建数组存放3名老师,通过函数给每个老师及所带的学生赋值;
3、最终打印出老师数据以及老师所带的学生数据
以下是本篇文章正文内容
视频里,老师是把案例里的内容全部放在了一个文件里(.cpp),见结构体案例1,但在以后的编程中,我们不能每次都把所有的代码放一个文件里。因此我这里又额外创建了两个文件(.cpp),分别用来放AllocateSpace函数(用来给老师、学生赋值)和PrintInfo函数(用来打印老师、学生信息)。
那么问题来了,在每个.cpp文件里,由于都涉及到老师和学生的结构体,那就需要在开头定义结构体,但为了省事,我想找到一种只定义一次的方法。
还真被我找到了,我目前找的方法是“定义全局结构体”,解决方法是在头文件里定义结构体。
一、创建头文件(P70_case1.h)
#include<iostream>
using namespace std;
#include<string.h>
typedef struct student
{
string name;
int score;
};
typedef struct teacher
{
string name;
struct student sarray[5];
};
void AllocateSpace(struct teacher tarray[], int len);
void PrintInfo(struct teacher tarray[], int len);
二、创建main函数(P70_case1.cpp)
#include<iostream>
using namespace std;
#include<string.h>
#include "P70_case1.h"
int main()
{
teacher tarray[3];
int len = sizeof(tarray) / sizeof(tarray[0]);
AllocateSpace(tarray, len);
PrintInfo(tarray, len);
system("pause");
return 0;
}
三、创建AllocateSpace函数和PrintInfo函数
1、创建AllocateSpace函数(AllocateSpace.cpp)
#include "P70_case1.h"
#include <string.h>
#include <ctime>
//extern student sarry[];
//extern teacher tarry[];
void AllocateSpace(struct teacher tarray[], int len)
{
string nameseed = "ABCDE";
srand((unsigned int)time(NULL));
for (int i = 0; i < len; i++)
{
tarray[i].name = "Teacher_";
tarray[i].name += nameseed[i];
for (int j = 0; j < 5; j++)
{
tarray[i].sarray[j].name = "Student_";
tarray[i].sarray[j].name += nameseed[j];
int random = rand() % 61 + 40;
tarray[i].sarray[j].score = random;
}
}
cout << endl;
}
2、创建PrintInfo函数(PrintInfo.cpp)
#include "P70_case1.h"
#include <string.h>
void PrintInfo(struct teacher tarray[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "Teacher's name: " << tarray[i].name << endl;
for (int j = 0; j < 5; j++)
{
cout << "\tStudent's name: " << tarray[i].sarray[j].name
<< " Student's score: " << tarray[i].sarray[j].score << endl;
}
}
}
运行P70_case1.cpp即可
完结