This repository has been archived on 2020-04-08. You can view files and clone it, but cannot push or open issues or pull requests.
Files
Indoor/data/csv.h
2018-10-25 11:50:12 +02:00

106 lines
1.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* © Copyright 2014 Urheberrechtshinweis
* Alle Rechte vorbehalten / All Rights Reserved
*
* Programmcode ist urheberrechtlich geschuetzt.
* Das Urheberrecht liegt, soweit nicht ausdruecklich anders gekennzeichnet, bei Frank Ebner.
* Keine Verwendung ohne explizite Genehmigung.
* (vgl. § 106 ff UrhG / § 97 UrhG)
*/
#ifndef CSV_H
#define CSV_H
#include <vector>
#include <string>
#include <fstream>
#include "../misc/Debug.h"
#include "../Exception.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());
// sanity check
if (!inp) {
throw Exception("failed to open file: " + file);
}
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