利用C++标准模板库(STL)的容器类vector 实现对一批学生信息的统计、管理功能:1)从文件(studentstxt) 中读人如下信息:学号、姓名、性别、专业、年龄。其中每个学生一行,山表示空格符,《表示换行符,读入信息后将其放入容器: 13122004 日张三口 M 山计算机L 20 13124002 口李四口F 口物理L 19 6ones~ 13226009 山李四LFL数学口 21K 2)计算并返回平均年龄。 3)分别统计“计算机专业的人数”“数学专业的人数”“物理专业女生的人数”并输出到显示器。 4)分别按学号、姓名、专业对学生信息进行排序并把排序后的学生信息输出到显示器5)把“计算机”专业的学生信息按 1)所示的格式写入文件(students computer.txt)。 要求:除了 1),其他问题不允许显式地使用循环。
时间: 2024-03-25 12:42:15 浏览: 160
C++编程实现学生基本信息管理程序
文件1:student.h
```c++
#pragma once
#include <string>
struct Student {
std::string id;
std::string name;
char gender;
std::string major;
int age;
};
```
文件2:main.cpp
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include "student.h"
int main() {
std::vector<Student> students;
std::ifstream infile("studentstxt");
std::string id, name, major;
char gender;
int age;
while (infile >> id >> name >> gender >> major >> age) {
students.push_back({id, name, gender, major, age});
}
//计算平均年龄
double averageAge = static_cast<double>(std::accumulate(students.begin(), students.end(), 0, [](int sum, Student s) {
return sum + s.age;
})) / students.size();
std::cout << "Average age: " << averageAge << std::endl;
//计算专业和性别数量
int computerCount = std::count_if(students.begin(), students.end(), [](Student s) {
return s.major == "计算机";
});
int mathCount = std::count_if(students.begin(), students.end(), [](Student s) {
return s.major == "数学";
});
int physicsFemaleCount = std::count_if(students.begin(), students.end(), [](Student s) {
return s.major == "物理" && s.gender == 'F';
});
std::cout << "Computer students count: " << computerCount << std::endl;
std::cout << "Math students count: " << mathCount << std::endl;
std::cout << "Physics female students count: " << physicsFemaleCount << std::endl;
//按学号排序
std::sort(students.begin(), students.end(), [](Student s1, Student s2) {
return s1.id < s2.id;
});
for (auto s : students) {
std::cout << s.id << " " << s.name << " " << s.gender << " " << s.major << " " << s.age << std::endl;
}
//按姓名排序
std::sort(students.begin(), students.end(), [](Student s1, Student s2) {
return s1.name < s2.name;
});
for (auto s : students) {
std::cout << s.id << " " << s.name << " " << s.gender << " " << s.major << " " << s.age << std::endl;
}
//按专业排序
std::sort(students.begin(), students.end(), [](Student s1, Student s2) {
return s1.major < s2.major;
});
for (auto s : students) {
std::cout << s.id << " " << s.name << " " << s.gender << " " << s.major << " " << s.age << std::endl;
}
//写入计算机专业学生信息
std::ofstream outfile("students_computer.txt");
std::copy_if(students.begin(), students.end(), std::ostream_iterator<Student>(outfile, "\n"), [](Student s) {
return s.major == "计算机";
});
return 0;
}
```
阅读全文