我有点搞不懂这个
在for循环中第五次输入学生的姓名和分数,为什么不会覆盖前面四次对学生输入的姓名和分数,最后会完完整整的打印出来?
#include<iostream>
#include<string>
using namespace std;
struct student
{
string name;
int score;
};
struct teacher
{
string name;
struct student s1[5];
};
void teacherspace(teacher t1[])
{
for (int i = 0; i < 3; i++)
{
cout << "输入老师的姓名" << endl;
cin >> t1[i].name;//输入老师姓名
cout << "输入学生的姓名和分数" << endl;
for (int stu = 0; stu < 5; stu++)//利用函数输入学生信息
{
int random = rand() % 60 + 40;
cin >> t1[i].s1[stu].name;//输入学生姓名
t1[i].s1[stu].score=random;//输入学生分数
}
}
}
void print(teacher t1[])//输出结构体的数据
{
for (int a = 0; a < 3; a++)
{
cout << t1[a].name << endl;//输出老师姓名
for (int b = 0; b < 5; b++)
{
cout << t1[a].s1[b].name << endl;//输出学生姓名
cout << t1[a].s1[b].score << endl;//输出学生分数
}
}
}
int main()
{
teacher t1[3];
teacherspace(t1);
print(t1);
return 0;
}
因为存储到了不同的数组元素啊。你定义的教师结构中有5个学生信息,for循环正好是分别输入5个学生信系,自然不会覆盖了
是没清空吧?
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!