1#include <iostream>
2#include <fstream>
3#include <sstream>
4#include <vector>
5#include <string>
6#include <iomanip>
7
8class Student {
9private:
10 int m_rollNumber;
11 std::string m_name;
12 std::string m_course;
13 double m_gpa;
14
15public:
16 Student(int roll, const std::string& name, const std::string& course, double gpa)
17 : m_rollNumber(roll), m_name(name), m_course(course), m_gpa(gpa) {}
18
19 int getRoll() const { return m_rollNumber; }
20 std::string getName() const { return m_name; }
21 std::string getCourse() const { return m_course; }
22 double getGpa() const { return m_gpa; }
23
24 std::string toCsv() const {
25 std::stringstream ss;
26 ss << m_rollNumber << "," << m_name << "," << m_course << "," << m_gpa;
27 return ss.str();
28 }
29};
30
31class StudentRegistry {
32private:
33 std::vector<Student> m_records;
34 const std::string m_filepath = "students_db.csv";
35
36public:
37 StudentRegistry() {
38 loadFromFile();
39 }
40
41 void addStudent(int roll, const std::string& name, const std::string& course, double gpa) {
42 m_records.emplace_back(roll, name, course, gpa);
43 saveToFile();
44 std::cout << "✅ Student added successfully!\n";
45 }
46
47 void displayAll() const {
48 if (m_records.empty()) {
49 std::cout << "No records found.\n";
50 return;
51 }
52
53 std::cout << "\n" << std::left << std::setw(10) << "Roll"
54 << std::setw(25) << "Name"
55 << std::setw(20) << "Course"
56 << std::setw(10) << "GPA" << "\n";
57 std::cout << std::string(65, '-') << "\n";
58
59 for (const auto& s : m_records) {
60 std::cout << std::left << std::setw(10) << s.getRoll()
61 << std::setw(25) << s.getName()
62 << std::setw(20) << s.getCourse()
63 << std::setw(10) << std::fixed << std::setprecision(2) << s.getGpa() << "\n";
64 }
65 }
66
67 void saveToFile() const {
68 std::ofstream file(m_filepath);
69 if (file) {
70 for (const auto& s : m_records) {
71 file << s.toCsv() << "\n";
72 }
73 }
74 }
75
76 void loadFromFile() {
77 std::ifstream file(m_filepath);
78 if (!file) return;
79
80 m_records.clear();
81 std::string line;
82 while (std::getline(file, line)) {
83 if (line.empty()) continue;
84 std::stringstream ss(line);
85 std::string rollStr, name, course, gpaStr;
86
87 if (std::getline(ss, rollStr, ',') &&
88 std::getline(ss, name, ',') &&
89 std::getline(ss, course, ',') &&
90 std::getline(ss, gpaStr, ',')) {
91 m_records.emplace_back(std::stoi(rollStr), name, course, std::stod(gpaStr));
92 }
93 }
94 }
95};
96
97int main() {
98 StudentRegistry registry;
99 registry.addStudent(101, "Deepak Yadav", "Modern C++", 9.2);
100 registry.addStudent(102, "Ananya Jain", "Java Mastery", 8.9);
101 registry.displayAll();
102 return 0;
103}