c++动态数组学生信息
时间: 2023-08-03 18:14:15 浏览: 51
以下是一个简单的示例代码,展示如何使用C++动态数组来存储学生信息:
```cpp
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int age;
double gpa;
};
int main() {
int numStudents;
cout << "Enter the number of students: ";
cin >> numStudents;
Student* students = new Student[numStudents];
for (int i = 0; i < numStudents; i++) {
cout << "Enter name of student " << i+1 << ": ";
cin >> students[i].name;
cout << "Enter age of student " << i+1 << ": ";
cin >> students[i].age;
cout << "Enter GPA of student " << i+1 << ": ";
cin >> students[i].gpa;
}
cout << endl << "Student Information:" << endl;
for (int i = 0; i < numStudents; i++) {
cout << "Name: " << students[i].name << endl;
cout << "Age: " << students[i].age << endl;
cout << "GPA: " << students[i].gpa << endl << endl;
}
delete[] students;
return 0;
}
```
在这个示例中,我们使用动态数组来存储学生结构体类型的信息。首先,我们通过用户输入确定了需要存储的学生数量。然后,我们使用 `new` 运算符来分配一个大小为 `numStudents` 的 `Student` 动态数组。接下来,我们通过循环依次为每个学生输入姓名、年龄和GPA,并将它们存储在动态数组中。最后,我们再次循环遍历整个动态数组,并输出每个学生的信息。最后,我们使用 `delete[]` 运算符来释放动态数组所占用的内存空间。