Lesson 4 of 5
Mini Project Part 10 - CSV File Parser
Build a production-quality CSV parser that: reads files with `ifstream`, handles quoted fields with commas inside, provides typed column access, uses `std::optional` for missing values, integrates `std::filesystem` for path validation, and demonstrates complete error handling with custom exceptions. The parsed data feeds a simple aggregate report.
CSV Parser - fstream + Parsing + Aggregation
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <optional>
#include <stdexcept>
#include <algorithm>
#include <numeric>
#include <filesystem>
#include <iomanip>
namespace fs = std::filesystem;
class CsvError : public std::runtime_error {
size_t line_;
public:
CsvError(size_t ln, const std::string& msg)
: std::runtime_error("Line " + std::to_string(ln) + ": " + msg)
, line_(ln) {}
size_t line() const { return line_; }
};
// ── Parse a single CSV line handling quoted fields ────────────
std::vector<std::string> parse_csv_line(const std::string& line) {
std::vector<std::string> fields;
std::string field;
bool in_quotes = false;
for (size_t i = 0; i < line.size(); ++i) {
char c = line[i];
if (c == '"') {
if (in_quotes && i+1 < line.size() && line[i+1] == '"') {
field += '"'; ++i; // escaped quote ""
} else {
in_quotes = !in_quotes;
}
} else if (c == ',' && !in_quotes) {
fields.push_back(std::move(field));
field.clear();
} else {
field += c;
}
}
fields.push_back(std::move(field));
return fields;
}
struct CsvTable {
std::vector<std::string> headers;
std::vector<std::vector<std::string>> rows;
std::optional<double> get_double(size_t row, size_t col) const {
if (row >= rows.size() || col >= rows[row].size()) return std::nullopt;
const auto& s = rows[row][col];
if (s.empty()) return std::nullopt;
try {
size_t idx;
double v = std::stod(s, &idx);
if (idx != s.size()) return std::nullopt;
return v;
} catch (...) { return std::nullopt; }
}
size_t col_index(const std::string& name) const {
auto it = std::find(headers.begin(), headers.end(), name);
if (it == headers.end())
throw std::out_of_range("Column not found: " + name);
return static_cast<size_t>(it - headers.begin());
}
};
CsvTable read_csv(const fs::path& path) {
if (!fs::exists(path)) throw std::runtime_error("File not found: " + path.string());
std::ifstream file(path);
if (!file) throw std::runtime_error("Cannot open: " + path.string());
CsvTable table;
std::string line;
size_t lineno = 0;
// Header row
if (!std::getline(file, line)) throw CsvError(1, "Empty file");
++lineno;
table.headers = parse_csv_line(line);
while (std::getline(file, line)) {
++lineno;
if (line.empty()) continue;
auto fields = parse_csv_line(line);
if (fields.size() != table.headers.size()) {
throw CsvError(lineno, "Expected " + std::to_string(table.headers.size()) +
" fields, got " + std::to_string(fields.size()));
}
table.rows.push_back(std::move(fields));
}
return table;
}
int main() {
// Create a sample CSV for demo
fs::path csv_path = "students.csv";
{
std::ofstream f(csv_path);
f << "name,grade,year
";
f << "Alice,95.0,3
";
f << "Bob,,1
"; // missing grade
f << ""Smith, Charlie",88.5,2
"; // quoted name with comma
f << "Diana,72.0,3
";
f << "Eve,60.5,4
";
}
try {
auto table = read_csv(csv_path);
std::cout << "Headers:";
for (const auto& h : table.headers) std::cout << " " << h;
std::cout << "
Rows: " << table.rows.size() << "
";
size_t grade_col = table.col_index("grade");
size_t name_col = table.col_index("name");
std::vector<double> grades;
for (size_t i = 0; i < table.rows.size(); ++i) {
const auto& name = table.rows[i][name_col];
auto grade = table.get_double(i, grade_col);
if (grade) {
grades.push_back(*grade);
std::cout << std::setw(20) << name << ": " << *grade << "
";
} else {
std::cout << std::setw(20) << name << ": (no grade)
";
}
}
if (!grades.empty()) {
double avg = std::accumulate(grades.begin(), grades.end(), 0.0) / grades.size();
double mx = *std::max_element(grades.begin(), grades.end());
std::cout << "
Average: " << std::fixed << std::setprecision(2) << avg << "
";
std::cout << "Best: " << mx << "
";
}
} catch (const CsvError& e) {
std::cerr << "CSV parse error at " << e.what() << "
";
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "
";
}
fs::remove(csv_path);
return 0;
}Common Mistakes
- Not handling CRLF line endings on Windows - `std::getline` reads until `\n` but leaves `\r` at the end of lines if the file was written with CRLF. Strip trailing `\r`: `if (!line.empty() && line.back() == '\r') line.pop_back();`
- Assuming column count matches on every row - CSV files in the wild have inconsistent column counts. Validate row count == header count and throw CsvError with the line number for diagnosis.
- Storing all data in memory for large files - `CsvTable` holds all rows in memory. For files > 100MB, use a streaming parser that processes one row at a time without storing all rows.
Tip
Tip
Practice Mini Project Part 10 CSV File Parser in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Robust File Handling: std::ifstream, std::stringstream Tokenization & Exception Boundaries
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Part 10 CSV File Parser from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Mini Project Part 10 CSV File Parser is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- Build a production-quality CSV parser that: reads files with `ifstream`, handles quoted fields with commas inside, provides typed column access, uses `std::optional` for missing values, integrates `std::filesystem` for path validation, and demonstrates complete error handling with custom exceptions.
- Not handling CRLF line endings on Windows - `std::getline` reads until `\n` but leaves `\r` at the end of lines if the file was written with CRLF. Strip trailing `\r`: `if (!line.empty() && line.back() == '\r') line.pop_back();`
- Assuming column count matches on every row - CSV files in the wild have inconsistent column counts. Validate row count == header count and throw CsvError with the line number for diagnosis.
- Storing all data in memory for large files - `CsvTable` holds all rows in memory. For files > 100MB, use a streaming parser that processes one row at a time without storing all rows.
Finished this lesson?