Medusa  1.1
Coordinate Free Mehless Method implementation
CSV.cpp
Go to the documentation of this file.
1 #include "medusa/bits/io/CSV.hpp"
2 
8 namespace mm {
9 
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));
13 
14  std::vector<double> data;
15  std::string s;
16  while (getline(f, s)) {
17  try {
18  data.push_back(std::stod(s));
19  } catch(const std::invalid_argument& e) {
20  assert_msg(false, "Failed parsing '%s' to double.", s);
21  }
22  }
23  return data;
24 }
25 
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));
29 
30  std::vector<std::vector<std::string>> lines;
31  std::string s;
32  while (getline(f, s)) lines.push_back(split(s, separator));
33 
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());
40  }
41 
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) {
45  try {
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]);
49  }
50  }
51  }
52  return data;
53 }
54 
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;
58  do {
59  pos = str.find(separator, prev);
60  if (pos == std::string::npos) pos = str.length();
61  tokens.emplace_back(str.substr(prev, pos-prev));
62  prev = pos + 1;
63  } while (pos < str.length() && prev < str.length());
64  if (prev == str.length()) tokens.emplace_back("");
65  return tokens;
66 }
67 
68 } // namespace mm
mm
Root namespace for the whole library.
Definition: Gaussian.hpp:14
mm::sh::str
std::string str(shape_flags f)
Convert shape flags to a string representation.
Definition: shape_flags.hpp:32
mm::CSV::read2d
static std::vector< std::vector< double > > read2d(const std::string &filename, char separator=',')
Reads a CSV file to a vector of vectors of doubles.
Definition: CSV.cpp:26
assert_msg
#define assert_msg(cond,...)
Assert with better error reporting.
Definition: assert.hpp:75
CSV.hpp
mm::CSV::split
static std::vector< std::string > split(const std::string &str, char separator)
Splits given string into a vector of strings on the given separator.
Definition: CSV.cpp:55
mm::CSV::read
static std::vector< double > read(const std::string &filename)
Reads a CSV file to a vector of doubles.
Definition: CSV.cpp:10