C++ · Module 19 · Lesson 21 min read

Project: Student Records with STL & Files

Features checklist

  1. Student with roll number, name and marks in several subjects
  2. Compute total, percentage, grade and pass/fail (any subject below 40 = fail)
  3. Add / update / remove students (unique roll numbers)
  4. Search by roll number (O(log n) with std::map) or by name (case-insensitive)
  5. Rank students by percentage (ties broken by name) with std::sort
  6. Statistics: class average, topper per subject, pass rate, grade distribution
  7. Save to / load from CSV, skipping invalid lines with a message

Design

arduino
struct Student { int roll; std::string name; std::array<int, 3> marks; ... };
class Classroom {
    std::map<int, Student> students_;   // sorted by roll, fast lookup
public: add, remove, find, ranked(), stats(), save(path), load(path)
};

Concepts practised

std::map, std::array, std::vector + std::sort with custom comparators, std::accumulate, std::max_element, std::count_if, string streams for CSV, file streams, exceptions, std::format tables.

Quality checklist ✅

  • Reject duplicate roll numbers and marks outside 0–100
  • Round-trip test: save → load → identical data
  • Output aligned in a table

Extensions

More subjects from a config file, attendance tracking, report cards per student (one text file each), export to JSON, a GPA system.

Example

C++
#include <algorithm>
#include <array>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <map>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

const std::array<std::string, 3> SUBJECTS = { "Math", "Science", "English" };

struct Student {
    int roll;
    std::string name;
    std::array<int, 3> marks;

    int total() const { return std::accumulate(marks.begin(), marks.end(), 0); }
    double percent() const { return total() / 3.0; }
    bool passed() const { return std::all_of(marks.begin(), marks.end(), [](int m) { return m >= 40; }); }
    char grade() const {
        if (!passed()) return 'F';
        double p = percent();
        return p >= 80 ? 'A' : p >= 65 ? 'B' : p >= 50 ? 'C' : 'D';
    }
};

class Classroom {
public:
    void add(const Student& s) {
        for (int m : s.marks) if (m < 0 || m > 100) throw std::invalid_argument("marks must be 0-100");
        if (!students_.try_emplace(s.roll, s).second) throw std::invalid_argument("duplicate roll " + std::to_string(s.roll));
    }
    bool remove(int roll) { return students_.erase(roll) == 1; }
    std::vector<Student> ranked() const {
        std::vector<Student> v;
        for (const auto& [roll, s] : students_) v.push_back(s);
        std::sort(v.begin(), v.end(), [](const Student& a, const Student& b) {
            if (a.total() != b.total()) return a.total() > b.total();
            return a.name < b.name;
        });
        return v;
    }
    void stats() const {
        auto v = ranked();
        double avg = std::accumulate(v.begin(), v.end(), 0.0, [](double t, const Student& s) { return t + s.percent(); }) / v.size();
        auto pass = std::count_if(v.begin(), v.end(), [](const Student& s) { return s.passed(); });
        std::cout << std::format("class average {:.1f}%, passed {}/{}\n", avg, pass, v.size());
        for (std::size_t i = 0; i < SUBJECTS.size(); ++i) {
            auto best = std::max_element(v.begin(), v.end(), [i](const Student& a, const Student& b) { return a.marks[i] < b.marks[i]; });
            std::cout << std::format("  top in {:<8} {} ({})\n", SUBJECTS[i], best->name, best->marks[i]);
        }
    }
    void save(const std::string& path) const {
        std::ofstream out(path);
        out << "roll,name,math,science,english\n";
        for (const auto& [roll, s] : students_)
            out << roll << ',' << s.name << ',' << s.marks[0] << ',' << s.marks[1] << ',' << s.marks[2] << '\n';
    }
    int load(const std::string& path) {
        std::ifstream in(path);
        std::string line;
        std::getline(in, line);
        int loaded = 0, line_no = 1;
        while (std::getline(in, line)) {
            ++line_no;
            std::istringstream row(line);
            std::string roll, name, a, b, c;
            std::getline(row, roll, ','); std::getline(row, name, ',');
            std::getline(row, a, ','); std::getline(row, b, ','); std::getline(row, c, ',');
            try {
                add({ std::stoi(roll), name, { std::stoi(a), std::stoi(b), std::stoi(c) } });
                ++loaded;
            } catch (const std::exception& e) {
                std::cout << "  skipped line " << line_no << ": " << e.what() << '\n';
            }
        }
        return loaded;
    }
    std::size_t size() const { return students_.size(); }
private:
    std::map<int, Student> students_;
};

int main() {
    Classroom c;
    c.add({ 1, "Asha", { 92, 88, 79 } });
    c.add({ 2, "Ravi", { 65, 72, 58 } });
    c.add({ 3, "Sita", { 88, 95, 90 } });
    c.add({ 4, "Hari", { 35, 60, 55 } });
    c.add({ 5, "Gita", { 70, 68, 74 } });
    try { c.add({ 2, "Copy", { 1, 1, 1 } }); } catch (const std::exception& e) { std::cout << "error: " << e.what() << '\n'; }

    std::cout << std::format("{:<4}{:<6}{:>6}{:>8}{:>7}\n", "#", "Name", "Total", "%", "Grade");
    int rank = 0;
    for (const auto& s : c.ranked())
        std::cout << std::format("{:<4}{:<6}{:>6}{:>8.1f}{:>7}\n", ++rank, s.name, s.total(), s.percent(), s.grade());
    c.stats();

    c.save("students.csv");
    {
        std::ofstream extra("students.csv", std::ios::app);
        extra << "6,Bad,abc,1,1\n" << "7,Mina,101,50,50\n";
    }
    Classroom reloaded;
    std::cout << "reloading:\n";
    int n = reloaded.load("students.csv");
    std::cout << "loaded " << n << " students\n";
    std::filesystem::remove("students.csv");
    return 0;
}

/* Output:
error: duplicate roll 2
#   Name   Total       %  Grade
1   Sita     273    91.0      A
2   Asha     259    86.3      A
3   Gita     212    70.7      B
4   Ravi     195    65.0      B
5   Hari     150    50.0      F
class average 72.6%, passed 4/5
  top in Math     Asha (92)
  top in Science  Sita (95)
  top in English  Sita (90)
reloading:
  skipped line 7: stoi
  skipped line 8: marks must be 0-100
loaded 5 students
*/