C++自学笔记(结构体实战)

    科技2023-09-16  102

    结构体案例实战

    案例一

    一个老师带五个学生,总共有五个老师设计老师和学生的结构体,在老师的结构体中,有老师的姓名和他的学生学生的属性有姓名、分数,创建数组存放3个老师,手动输入学生信息打印老师和学生的数据 #include<string> #include<iostream> using namespace std; /* - 一个老师带stu_num个学生,总共有三个老师 - 设计老师和学生的结构体,在老师的结构体中,有老师的姓名和他的学生 - 学生的属性有姓名、分数,创建数组存放3个老师 - 打印老师和学生的数据 */ int stu_num = 3; int tea_num = 3; //结构体定义 struct student { string name; int score; }; struct teacher { string name; struct student student_arry[5]; }; //通过函数给学生赋值 void stu_name_score(struct teacher teacher_arry[],int len) { for (int i = 0; i < tea_num; i++) { string tname; for (int t = 0; t < stu_num; t++) { switch (i) { case 0:tname = "甲老师"; break; case 1:tname = "乙老师"; break; case 2:tname = "丙老师"; break; } cout << tname << "第" << t + 1 << "个学生 姓名:" << endl; cin >> teacher_arry[i].student_arry[t].name; cout << tname << "第" << t + 1 << "个学生 成绩:" << endl; cin >> teacher_arry[i].student_arry[t].score; } cout <<tname<<"的学生及其分数分别为:"; for (int j = 0; j < stu_num; j++) { cout << teacher_arry[i].student_arry[j].name << ":" << teacher_arry[i].student_arry[j].score << " "; } cout << endl; } }; int main() { struct teacher teacher_arry[3] = { {"老师甲"},{"老师乙"},{"老师丙"} }; //只需传入数组名teacher_arry即可,不需要加[] stu_name_score(teacher_arry,tea_num); system("pause"); }
    Processed: 0.016, SQL: 8