/* * © 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 #include #include #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 { }; /** one csv document */ struct Doc : std::vector { }; 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