#include <iostream>
#include <fstream>
using namespace std;

// 定义学生类 CStudent
// 至少要有无参构造函数和有参构造函数
class CStudent {
public:
    CStudent() {}
    CStudent(int id, int score) : id(id), score(score) {}

    int getScore() const { return score; }

private:
    int id;
    int score;
};

int main()
{
    ifstream data('data.txt');  // 打开文件
    string id_title;            // 表头
    string score_title;         // 表头
    int id;                     // 数据
    int score;                  // 数据

    // 定义存放学生信息的长度为100的数组listStudents
    CStudent listStudents[100];

    // 读取文件
    if (data.is_open())          // 文件打开是否成功?
    {
        data >> id_title;
        data >> score_title;

        int i = 0;              // 一个整型变量i,并初始化为0

        while (!data.eof())      // 文件是否读到了末尾?
        {
            data >> id;
            data >> score;

            // 以id 和 score为参数,实例化一个CStudent类型的对象,并
            // 将其赋给listStudents数组的第i个对象,并让i的值增加1
            listStudents[i] = CStudent(id, score);
            i++;
        }

        // 编写循环语句,依次读取数组listStudents中的元素的成绩
        // 同时记录不及格学生人数及学生总成绩
        // 计算学生平均成绩
        int totalScore = 0;     // 记录学生总成绩
        int numFail = 0;        // 记录不及格学生人数

        for (int j = 0; j < i; j++) {
            int studentScore = listStudents[j].getScore();
            totalScore += studentScore;

            if (studentScore < 60) {
                numFail++;
            }
        }

        double averageScore = static_cast<double>(totalScore) / i;

        // 输出学生平均成绩、不及格学生人数等信息
        cout << '平均成绩:' << averageScore << endl;
        cout << '不及格学生人数:' << numFail << endl;
    }

    return 0;
}

代码解释:

  1. 包含头文件:
    • #include <iostream>: 用于输入输出流操作,例如 cincout
    • #include <fstream>: 用于文件输入输出流操作,例如读取和写入文件。
  2. 定义学生类 CStudent
    • 包含私有成员变量 idscore,分别表示学生的ID和成绩。
    • 包含公有构造函数,用于初始化学生对象。
    • 包含公有成员函数 getScore,用于获取学生的成绩。
  3. 主函数 main
    • 定义变量 data,用于打开名为 'data.txt' 的文件,并使用 ifstream 类型表示输入文件流。
    • 定义变量 id_titlescore_title,用于存储文件头部的两列标题。
    • 定义变量 idscore,用于存储从文件中读取的单个学生数据。
    • 定义数组 listStudents,用于存储所有学生的 CStudent 对象。
    • 使用 if (data.is_open()) 判断文件是否成功打开。
    • 如果文件打开成功,则读取文件头部两行,并将数据存储在 id_titlescore_title 中。
    • 使用 while (!data.eof()) 循环读取文件中的每一行数据,直到文件末尾。
    • 在循环中,使用 data >> id >> score; 读取学生的ID和成绩,并使用读取到的数据创建一个新的 CStudent 对象,将其存储在 listStudents 数组中。
    • 读取完所有数据后,使用 for 循环遍历 listStudents 数组,计算学生的总成绩、不及格人数和平均成绩。
    • 最后,使用 cout 输出计算结果。

注意事项:

  • 在实际应用中,需要根据实际情况修改文件名、文件路径、数据格式等。
  • 需要确保文件 'data.txt' 存在,并且格式正确,否则程序可能会出现错误。
  • 可以根据需要添加错误处理机制,例如在文件打开失败时输出错误信息。
  • 可以使用更安全的数据类型和函数,例如使用 std::vector 存储学生数据,使用 std::getline 读取文件每一行数据。

希望以上解释能够帮助您理解这段代码。

C++读取文件数据并计算学生成绩

原文地址: https://www.cveoy.top/t/topic/byo2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录