added csv parsing
This commit is contained in:
88
data/csv.h
Normal file
88
data/csv.h
Normal 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
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <iomanip>
|
#include <iomanip>
|
||||||
|
#include <sstream>
|
||||||
#include "Time.h"
|
#include "Time.h"
|
||||||
|
|
||||||
#include "log/LoggerCOUT.h"
|
#include "log/LoggerCOUT.h"
|
||||||
|
|||||||
Reference in New Issue
Block a user