-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpense.cpp
More file actions
36 lines (33 loc) · 1.1 KB
/
Expense.cpp
File metadata and controls
36 lines (33 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "../include/Expense.h"
#include <sstream>
#include <iomanip>
std::string Expense::to_csv() const {
std::ostringstream oss;
// simple CSV, no escaping for commas in description for brevity
oss << id << ',' << date << ',' << category << ',' << description << ',' << std::fixed << std::setprecision(2) << amount;
return oss.str();
}
bool Expense::from_csv(const std::string &line, Expense &out) {
std::istringstream iss(line);
std::string token;
try {
// id
if (!std::getline(iss, token, ',')) return false;
out.id = std::stoi(token);
// date
if (!std::getline(iss, out.date, ',')) return false;
// category
if (!std::getline(iss, out.category, ',')) return false;
// description
if (!std::getline(iss, out.description, ',')) return false;
// amount
if (!std::getline(iss, token, ',')) {
// maybe EOF, try read rest
if (!std::getline(iss, token)) return false;
}
out.amount = std::stod(token);
} catch (...) {
return false;
}
return true;
}