Write save(students, path) and load(path) functions that store student records as one line each ("name,city,marks") and read them back into a vector; save, load and print the class topper.
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
struct Student { std::string name, city; int marks; };
void save(const std::vector<Student>& v, const std::filesystem::path& p) {
std::ofstream out(p);
for (const auto& s : v) out << s.name << ',' << s.city << ',' << s.marks << '\n';
}
std::vector<Student> load(const std::filesystem::path& p) {
std::vector<Student> v;
std::ifstream in(p);
for (std::string line; std::getline(in, line); ) {
std::stringstream ss(line);
Student s;
std::string m;
std::getline(ss, s.name, ',');
std::getline(ss, s.city, ',');
std::getline(ss, m);
s.marks = std::stoi(m);
v.push_back(s);
}
return v;
}
int main() {
auto p = std::filesystem::temp_directory_path() / "lf_class.csv";
save({{"Asha", "Pune", 91}, {"Ravi Kumar", "New Delhi", 78}, {"Meena", "Agra", 95}}, p);
auto loaded = load(p);
for (const auto& s : loaded) std::cout << s.name << " (" << s.city << "): " << s.marks << '\n';
auto top = std::max_element(loaded.begin(), loaded.end(), [](const auto& a, const auto& b) { return a.marks < b.marks; });
std::cout << "topper: " << top->name << '\n';
std::filesystem::remove(p);
return 0;
}
Asha (Pune): 91 Ravi Kumar (New Delhi): 78 Meena (Agra): 95 topper: Meena
Commas as separators let names and cities contain spaces; getline with ',' splits each line. The data survives the program ending – that is what files are for.