Skip to main content

Parsing Records from Files

beginner11 min readLesson 46 of 204

Module 6's mini-CSV pattern, now fed by a file: line loop + row stream + stoi/stod, plus std::filesystem basics.

The full pattern: file → lines → fields → typed data

#include <fstream>
#include <sstream>
#include <string>
#include <vector>

struct Item { std::string name; double price{}; int qty{}; };

std::vector<Item> load_items(const std::string& path) {
    std::ifstream in{path};
    std::vector<Item> items;
    std::string line;
    while (std::getline(in, line)) {
        if (line.empty()) continue;                 // tolerate blank lines
        std::istringstream row{line};
        std::string name, price_s, qty_s;
        std::getline(row, name, ',');
        std::getline(row, price_s, ',');
        std::getline(row, qty_s);
        items.push_back({name, std::stod(price_s), std::stoi(qty_s)});
    }
    return items;
}

Recognize every piece: the getline loop (13A), the row stream with delimiter (module 6), typed conversion. This function is the capstone's storage layer in embryo — data outlives the program because it is just text you can also read with any editor.

Writing records back

void save_items(const std::string& path, const std::vector<Item>& items) {
    std::ofstream out{path};
    for (const Item& it : items) {
        out << it.name << ',' << it.price << ',' << it.qty << '\n';
    }
}

Round-trip discipline: whatever you write must parse again. Choose one format, keep both sides in sync.

std::filesystem (a beginner's slice)

#include <filesystem>
namespace fs = std::filesystem;

fs::exists("data/items.csv")         // does it exist?
fs::file_size("data/items.csv")      // bytes
for (const auto& entry : fs::directory_iterator("data")) { /* entries */ }

Enough to check, measure, and list. Creating/removing directories and path manipulation grow in Intermediate.

A caution about numbers and locales

stod/cout number formatting follows the C locale by default (dot decimals). For this course's data files, dot decimals in, dot decimals out — consistency is the whole game.