C++ 结构体定义及循环赋值:学生信息管理示例
#include
struct Student { string name; int age; string major; };
int main() { const int numStudents = 20; // 学生总人数 Student students[numStudents];
for (int i = 0; i < numStudents; i++) {
cout << '请输入第' << i+1 << '个学生的姓名: ';
cin >> students[i].name;
cout << '请输入第' << i+1 << '个学生的年龄: ';
cin >> students[i].age;
cout << '请输入第' << i+1 << '个学生的专业: ';
cin >> students[i].major;
cout << endl;
}
// 输出学生信息
cout << '学生信息如下:' << endl;
for (int i = 0; i < numStudents; i++) {
cout << '姓名:' << students[i].name << endl;
cout << '年龄:' << students[i].age << endl;
cout << '专业:' << students[i].major << endl;
cout << endl;
}
return 0;
}
在这个程序中,我们首先定义了一个名为Student的结构体,包含了学生的姓名、年龄和专业三个成员变量。然后在main函数中,我们声明了一个大小为20的学生数组students。通过使用循环结构,依次对每个学生的姓名、年龄和专业进行赋值。最后,使用循环输出每个学生的信息。
原文地址: https://www.cveoy.top/t/topic/bsGF 著作权归作者所有。请勿转载和采集!