Line-by-Line Reading & CSV Parsing
The robust pattern ✅
std::ifstream in("data.csv");
std::string line;
std::getline(in, line); // skip the header row
while (std::getline(in, line)) {
if (line.empty()) continue;
std::istringstream row(line); // <sstream>
std::string date, category, amount_text;
std::getline(row, date, ',');
std::getline(row, category, ',');
std::getline(row, amount_text, ',');
...
}
String streams (<sstream>)
| Class | Use |
|---|---|
std::istringstream | read from a string as if it were a file |
std::ostringstream | build a string with <<, get it with .str() |
std::stringstream | both |
Validating each row
- Wrong number of fields → report the line number and skip
- Convert numbers with
std::stod/std::from_charsinside try/catch or with checks - Trim whitespace; handle Windows line endings (remove a trailing
'\r') - Count good and bad rows and report both
Writing CSV
out << date << ',' << category << ',' << amount << '\n';
Set the precision for money: out << std::fixed << std::setprecision(2);
Limitations of simple splitting ⚠️
Real CSV can contain quoted fields with commas ("Momo, Chowmein",450) and escaped quotes. For those, write a small state machine or use a CSV library.
Aggregating while reading
Combine with containers: std::map<std::string, double> totals; totals[category] += amount;
Example
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
struct Expense {
std::string date, category;
double amount;
};
std::vector<std::string> split(const std::string& line, char sep) {
std::vector<std::string> fields;
std::istringstream row(line);
for (std::string f; std::getline(row, f, sep);) fields.push_back(f);
return fields;
}
int main() {
{
std::ofstream out("statement.csv");
out << "date,category,amount\n"
<< "2026-11-01,Rent,15000\n"
<< "2026-11-02,Food,450.50\r\n" // a Windows line ending
<< "2026-11-02,Food\n" // missing field
<< "\n"
<< "2026-11-03,Travel,abc\n" // bad number
<< "2026-11-04,Food,1200\n";
}
std::ifstream in("statement.csv");
std::string line;
std::getline(in, line); // skip the header
std::vector<Expense> expenses;
int line_no = 1, bad = 0;
while (std::getline(in, line)) {
++line_no;
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.empty()) continue;
auto f = split(line, ',');
if (f.size() != 3) { std::cout << "line " << line_no << ": expected 3 fields, got " << f.size() << '\n'; ++bad; continue; }
try {
expenses.push_back({ f[0], f[1], std::stod(f[2]) });
} catch (const std::exception&) {
std::cout << "line " << line_no << ": invalid amount '" << f[2] << "'\n";
++bad;
}
}
std::cout << "loaded " << expenses.size() << " rows, skipped " << bad << '\n';
std::map<std::string, double> totals;
for (const auto& e : expenses) totals[e.category] += e.amount;
std::ofstream report("report.csv");
report << "category,total\n" << std::fixed << std::setprecision(2);
for (const auto& [cat, total] : totals) report << cat << ',' << total << '\n';
report.close();
std::ifstream check("report.csv");
std::cout << "report.csv:\n" << check.rdbuf(); // print the whole file
std::ostringstream summary;
summary << expenses.size() << " expenses in " << totals.size() << " categories";
std::cout << "summary string: " << summary.str() << '\n';
return 0;
}
/* Output:
line 4: expected 3 fields, got 2
line 6: invalid amount 'abc'
loaded 3 rows, skipped 2
report.csv:
category,total
Food,1650.50
Rent,15000.00
summary string: 3 expenses in 2 categories
*/