2.一个文本文件data1.txt,其内容为学生信息,每一行为一个信息,包含学号、姓名、数学成绩、英语成绩、物理成绩,数据之间以空白字符分隔。编程从该文件中读入这些信息,统计学生人数并求出每门成绩的平均分,最高分和最低分,在result.txt 中写入学生人数并求出每门成绩的平均分,最高分和最低分。C++C++
时间: 2024-02-01 22:16:25 浏览: 82
从文本文件输入n个同学的姓名、性别、成绩,按成绩又高到底的顺序输出所有学生信息,分别求出男同学、女同学的平均成绩并输出
4星 · 用户满意度95%
下面是一个简单的 C++ 实现:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct student {
string id;
string name;
int math;
int english;
int physics;
};
int main() {
ifstream fin("data1.txt");
if (!fin) {
cerr << "Cannot open file!" << endl;
return -1;
}
vector<student> students;
string line;
while (getline(fin, line)) {
student s;
stringstream ss(line);
ss >> s.id >> s.name >> s.math >> s.english >> s.physics;
students.push_back(s);
}
int count = students.size();
double math_sum = 0.0;
double english_sum = 0.0;
double physics_sum = 0.0;
int math_max = -1;
int english_max = -1;
int physics_max = -1;
int math_min = 101;
int english_min = 101;
int physics_min = 101;
for (auto s : students) {
math_sum += s.math;
english_sum += s.english;
physics_sum += s.physics;
math_max = max(math_max, s.math);
english_max = max(english_max, s.english);
physics_max = max(physics_max, s.physics);
math_min = min(math_min, s.math);
english_min = min(english_min, s.english);
physics_min = min(physics_min, s.physics);
}
double math_avg = math_sum / count;
double english_avg = english_sum / count;
double physics_avg = physics_sum / count;
ofstream fout("result.txt");
fout << "Number of students: " << count << endl;
fout << "Math average: " << math_avg << " Max: " << math_max << " Min: " << math_min << endl;
fout << "English average: " << english_avg << " Max: " << english_max << " Min: " << english_min << endl;
fout << "Physics average: " << physics_avg << " Max: " << physics_max << " Min: " << physics_min << endl;
fin.close();
fout.close();
return 0;
}
```
首先,我们打开文件并读取每一行,将每个学生的信息存储在一个结构体中,然后将所有学生存储在一个 vector 中。接下来,我们可以使用 for 循环来计算每个学生的成绩总分以及每个科目的最高分和最低分。最后,我们计算每个科目的平均分,并将结果写入另一个文件中。
阅读全文