89 lines
1.3 KiB
C++
89 lines
1.3 KiB
C++
#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
|