结构体主要内容包括:
结构体定义、结构体变量定义、结构体数组、结构体嵌套、函数中结构体的值传递和地址传递。整体来说难度不大,只不过自己在已有的数据类型上进行整合后的一种数据类型。
//20221016 结构体学习记录
#include<iostream>
#include<string> //字符串处理
#include<ctime> //随机数生成
using namespace std;
struct student //制定一个student结构体
{
string name;
int score;
};
struct teacher //制定一个teacher结构体
{
string name;
struct student sArr[4]; //结构体嵌套
};
struct school
{
string name;
int build_time;
};
void write_info(struct teacher* Arr,int L)
{
string num = "123456789";
for (int i=0; i < L; i++)
{
Arr[i].name = "teacher_"; //一般情况值传递用“.”,地址传递用“->”,但是对于数组的地址传递要用“.”
Arr[i].name += num[i];
for (int j=0; j < 4; j++)
{
Arr[i].sArr[j].name = "student_";//嵌套赋值的方法
Arr[i].sArr[j].name += num[j];
int random_num = rand() % 51;//返回一个0到50的随机数
Arr[i].sArr[j].score = random_num + 50;
}
}
}
void WriteSchoolInfo(struct school* SS)
{
SS->name = "DMU"; //地址传递
SS->build_time = 1909;
}
void print_info(struct school* SS,struct teacher* Arr, int L)
{
cout <<"\t\t " << SS->name << "---" << SS->build_time << endl << endl; //输出校名
for (int i=0; i < L; i++)
{
cout << "teachername: " << Arr[i].name << endl; //输出教师名
for (int j=0; j < 4; j++)
{
cout << "\tstudentname: " << 'T' <<i<<Arr[i].sArr[j].name <<
" score: " << Arr[i].sArr[j].score << endl; //输出学生名
}
}
}
int main()
{
//随机数种子
srand((unsigned int)time(NULL));
struct school School;
WriteSchoolInfo(&School);
struct teacher tArr[3];
int len = sizeof(tArr) / sizeof(tArr[0]);
write_info(tArr,len);
print_info(&School,tArr,len);
system("pause");
return 0;
}
运行结果
有问题欢迎一起学习交流,邮箱:bglei@foxmail.com