结构体数组(2)

结构体数组:

作用:将自定义的结构体放入数组中方便维护。

语法:struct 结构体名 数组名[元素个数] = {{}{}{}...};

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 //1.定义结构体
 6 struct Student
 7 {
 8     string name;
 9     int age;
10     int score;
11 };
12 
13 int main(void)
14 {
15     //2.创建结构体数组
16     struct Student student_array[3] = 
17     {
18         {"张三",18,150},
19         {"李四",20,120},
20         {"王五",22,90}
21     };
22 
23     //3.给结构体数组中的元素赋值
24     //student_array[3] = {"赵六",25,130};    //添加元素是非法操作,系统会报错
25 
26     student_array[1].name = "皮皮";    //修改元素,也可以修改其他的元素
27 
28     //4.遍历结构体数组
29     for (int i = 0; i < 3; i++)
30     {
31         cout << "姓名:" <<student_array[i].name << " 年龄:" << student_array[i].age<< " 分数:" << student_array[i].score << endl;
32     }
33 
34     system("pause");
35     return 0;
36 }

猜你喜欢

转载自www.cnblogs.com/huanian/p/12688124.html