#include
using namespace std;
struct Student {
string student_id;
string name;
string major;
int math_score;
int chinese_score;
int english_score;
int total_score;
};
// 解析数据文件中的一行并创建一个学生对象 Student parseStudent(const string& line) {
istringstream ss(line);
string student_id, name, major;
int math_score, chinese_score, english_score;
ss >> student_id >> name >> major >> math_score >> chinese_score >> english_score;
int total_score = math_score + chinese_score + english_score;
return { student_id, name, major, math_score, chinese_score, english_score, total_score };
}
// 从文件中读取数据并将其存储在学生对象的向量中
vector
vector<Student> students;
ifstream file(filename);
if (file.is_open()) {
string line;
while (getline(file, line)) {
students.push_back(parseStudent(line));
}
file.close();
}
else {
cerr << "错误:无法打开文件 " << filename << endl;
}
return students;
}
// 用于按总分排序的比较函数(降序) bool compareByTotalScore(const Student& a, const Student& b) {
return a.total_score > b.total_score;
}
void outputStudentsByMajor(const vector
map<string, vector<Student>> studentsByMajor;
map<string, int> totalScoreByMajor;
// 初始化每个专业的总评分为0
for (const auto& student : students) {
totalScoreByMajor[student.major] = 0;
}
// 将学生按专业分类,并计算每个专业的总评分
for (const auto& student : students) {
studentsByMajor[student.major].push_back(student);
totalScoreByMajor[student.major] += student.total_score;
}
// 输出每个专业的学生总评信息
for (auto& pair : studentsByMajor) {
sort(pair.second.begin(), pair.second.end(), compareByTotalScore);
cout << "专业:" << pair.first << endl;
cout << "总评:" << totalScoreByMajor[pair.first] << " 分" << endl;
for (size_t i = 0; i < pair.second.size(); ++i) {
cout << "排名 " << i + 1 << ":" << pair.second[i].name << "(" << pair.second[i].total_score << " 分)" << endl;
}
cout << endl;
}
}
// 按姓名查找学生信息
void searchStudentByName(const vector
bool found = false;
for (const auto& student : students) {
if (student.name == name) {
cout << "找到学生:" << endl;
cout << "姓名:" << student.name << endl;
cout << "学号:" << student.student_id<< endl;
cout<< "专业:" student.major<<endl;
cout<<"数学成绩:"<<student.math_score<<endl;
cout<<"语文成绩:"<<student.chinese_score<<endl;
cout<<"英语成绩:"<<student.english_score<<endl;
cout<<"总分:"<<student.total_score<<endl;
found = true;
break;
}
}
if (!found) {
cout << "未找到姓名为 '" << name << "' 的学生。" << endl;
}
}
int main() {
string filename = "data.txt";
vector<Student> students = readDataFromFile(filename);
cout << "按专业输出学生总评信息:" << endl;
outputStudentsByMajor(students);
// 按姓名查找学生信息
string nameToSearch = "张家辉"; // 修改此处为你想要查找的姓名
cout << "正在查找姓名为 '" << nameToSearch<< "' 的学生:" << endl;
searchStudentByName(students, nameToSearch);
return 0;
}
内容由零声教学AI助手提供,问题来源于学员提问