student.cpp

Download
cpp 61 lines 1.6 KB
 1#include "student.h"
 2#include <sstream>
 3#include <iomanip>
 4#include <stdexcept>
 5
 6/**
 7 * @brief Construct a new Student object
 8 */
 9Student::Student(int id, const std::string& name, const std::string& major, double gpa)
10    : id(id), name(name), major(major), gpa(gpa) {
11    if (gpa < 0.0 || gpa > 4.0) {
12        throw std::invalid_argument("GPA must be between 0.0 and 4.0");
13    }
14}
15
16/**
17 * @brief Convert student data to CSV format
18 * @return CSV string representation
19 */
20std::string Student::toCSV() const {
21    std::ostringstream oss;
22    oss << id << "," << name << "," << major << "," << std::fixed << std::setprecision(2) << gpa;
23    return oss.str();
24}
25
26/**
27 * @brief Create Student object from CSV string
28 * @param csvLine CSV formatted string (id,name,major,gpa)
29 * @return Student object
30 */
31Student Student::fromCSV(const std::string& csvLine) {
32    std::istringstream iss(csvLine);
33    std::string token;
34    int id;
35    std::string name, major;
36    double gpa;
37
38    // Parse CSV (simple implementation - assumes no commas in fields)
39    std::getline(iss, token, ',');
40    id = std::stoi(token);
41
42    std::getline(iss, name, ',');
43    std::getline(iss, major, ',');
44
45    std::getline(iss, token, ',');
46    gpa = std::stod(token);
47
48    return Student(id, name, major, gpa);
49}
50
51/**
52 * @brief Stream insertion operator for pretty printing
53 */
54std::ostream& operator<<(std::ostream& os, const Student& student) {
55    os << "ID: " << std::setw(5) << student.id
56       << " | Name: " << std::setw(20) << std::left << student.name
57       << " | Major: " << std::setw(15) << student.major
58       << " | GPA: " << std::fixed << std::setprecision(2) << student.gpa;
59    return os;
60}