c++

c++结构体数组怎么定义和使用

小亿
197
2023-11-09 10:04:07
栏目: 编程语言

在C++中,结构体数组的定义和使用可以通过以下步骤来实现:

  1. 定义一个结构体,其中包含要存储的数据类型。例如,定义一个表示学生信息的结构体:
struct Student {
    string name;
    int age;
    float score;
};
  1. 声明一个结构体数组,指定数组的大小。例如,声明一个包含3个学生信息的结构体数组:
Student students[3];
  1. 使用点运算符(.)为每个结构体数组元素设置值。例如,为每个学生信息设置值:
students[0].name = "Alice";
students[0].age = 20;
students[0].score = 85.5;

students[1].name = "Bob";
students[1].age = 21;
students[1].score = 90.0;

students[2].name = "Charlie";
students[2].age = 19;
students[2].score = 78.5;
  1. 使用下标运算符([])访问结构体数组中的元素。例如,输出每个学生的信息:
for (int i = 0; i < 3; i++) {
    cout << "Name: " << students[i].name << endl;
    cout << "Age: " << students[i].age << endl;
    cout << "Score: " << students[i].score << endl;
}

使用这些步骤,你就可以定义和使用结构体数组。注意,在使用结构体数组之前,需要包含相应的头文件(例如,iostream)和使用命名空间(例如,using namespace std)。

0
看了该问题的人还看了