added csv parsing

This commit is contained in:
2018-06-12 10:23:43 +02:00
parent b50995ffe6
commit 657e72b4c5
2 changed files with 89 additions and 0 deletions

88
data/csv.h Normal file
View File

@@ -0,0 +1,88 @@
#ifndef CSV_H
#define CSV_H
#include <vector>
#include <string>
#include <fstream>
#include "../misc/Debug.h"
class CSV {
static constexpr const char* NAME = "CSV";
public:
/** one column within the CSV */
struct Col {
std::string data;
Col(const std::string& data) : data(data) {;}
const std::string& asString() const {return data;}
int asInt() const {return std::stoi(data);}
long asLong() const {return std::stol(data);}
double asDouble() const {return std::stod(data);}
};
/** one row within the CSV */
struct Row : std::vector<Col> {
};
/** one csv document */
struct Doc : std::vector<Row> {
};
class Reader {
private:
const char sep;
public:
/** ctor */
Reader(const char sep) : sep(sep) {
}
/** read the given csv file */
Doc read(const std::string& file) {
Log::add(NAME, "reading file: " + file);
Doc doc;
std::ifstream inp(file.c_str());
int rowCnt = 0;
std::string line;
// read all lines within the CSV
while(std::getline(inp, line)) {
++rowCnt;
// split
Row row;
std::stringstream ss(line);
std::string tmp;
while(getline(ss, tmp, sep)){
row.push_back(Col(tmp));
}
// apend row
doc.push_back(row);
}
Log::add(NAME, "got " + std::to_string(rowCnt) + " rows");
return doc;
}
};
};
#endif // CSV_H

View File

@@ -4,6 +4,7 @@
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
#include "Time.h"
#include "log/LoggerCOUT.h"