可以给我一个结构体数组输入输出的实例吗
时间: 2023-10-18 12:30:14 浏览: 127
当结构体类型需要存储多组数据时,可以使用结构体数组。下面的代码展示了如何输入和输出一个结构体数组:
```cpp
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
float score;
};
int main() {
const int N = 3; // 数组大小
Student students[N];
// 输入结构体数组
for (int i = 0; i < N; i++) {
cout << "Enter info for student " << i+1 << ":" << endl;
cout << "Name: ";
cin >> students[i].name;
cout << "Age: ";
cin >> students[i].age;
cout << "Score: ";
cin >> students[i].score;
}
// 输出结构体数组
for (int i = 0; i < N; i++) {
cout << "Info for student " << i+1 << ":" << endl;
cout << "Name: " << students[i].name << endl;
cout << "Age: " << students[i].age << endl;
cout << "Score: " << students[i].score << endl;
}
return 0;
}
```
在上面的代码中,定义了一个结构体类型`Student`,其中包含三个成员变量`name`、`age`和`score`。在`main`函数中,定义了一个大小为3的结构体数组`students`,并利用`for`循环输入每个学生的信息。最后再利用`for`循环输出每个学生的信息。
输入结果示例:
```
Enter info for student 1:
Name: Alice
Age: 18
Score: 90
Enter info for student 2:
Name: Bob
Age: 19
Score: 85
Enter info for student 3:
Name: Charlie
Age: 20
Score: 95
```
输出结果示例:
```
Info for student 1:
Name: Alice
Age: 18
Score: 90
Info for student 2:
Name: Bob
Age: 19
Score: 85
Info for student 3:
Name: Charlie
Age: 20
Score: 95
```
阅读全文
相关推荐


















