10 std::vector<double>
CSV::read(
const std::string& filename) {
11 std::ifstream f(filename);
12 assert_msg(f.good(),
"Error opening CSV file '%s': %s.", filename, strerror(errno));
14 std::vector<double> data;
16 while (getline(f, s)) {
18 data.push_back(std::stod(s));
19 }
catch(
const std::invalid_argument& e) {
20 assert_msg(
false,
"Failed parsing '%s' to double.", s);
26 std::vector<std::vector<double>>
CSV::read2d(
const std::string& filename,
char separator) {
27 std::ifstream f(filename);
28 assert_msg(f.good(),
"Error opening CSV file '%s': %s.", filename, strerror(errno));
30 std::vector<std::vector<std::string>> lines;
32 while (getline(f, s)) lines.push_back(
split(s, separator));
34 size_t m = lines.size();
35 size_t n = lines[0].size();
36 for (
size_t i = 1; i < m; ++i) {
37 assert_msg(lines[i].size() == n,
"Not all rows in CSV file have the same number of "
38 "elements, row 1 has %d and row %d has %d.",
39 n, i, lines[i].size());
42 std::vector<std::vector<double>> data(m, std::vector<double>(n));
43 for (
size_t i = 0; i < m; ++i) {
44 for (
size_t j = 0; j < n; ++j) {
46 data[i][j] = std::stod(lines[i][j]);
47 }
catch(
const std::invalid_argument& e) {
48 assert_msg(
false,
"Failed parsing '%s' to double.", lines[i][j]);
55 std::vector<std::string>
CSV::split(
const std::string&
str,
char separator) {
56 std::vector<std::string> tokens;
57 size_t prev = 0, pos = 0;
59 pos =
str.find(separator, prev);
60 if (pos == std::string::npos) pos =
str.length();
61 tokens.emplace_back(
str.substr(prev, pos-prev));
63 }
while (pos <
str.length() && prev <
str.length());
64 if (prev ==
str.length()) tokens.emplace_back(
"");