#include "CSVReader.h" #include #include CSVReader::CSVReader() { } std::vector CSVReader::readCSV(std::string csvFilename) { std::vector entries; unsigned int errors = 0; std::ifstream csvFile{csvFilename}; std::string line; std::cout << "Loading data..." << std::endl; if (csvFile.is_open()) { while(std::getline(csvFile, line)) { try { OrderBookEntry obe = stringsToOBE(tokenise(line, ',')); entries.push_back(obe); } catch(const std::exception& e) { ++errors; } }// end of while std::cout << "Success! " << entries.size() << " entries found." << std::endl; if(errors > 0) std::cout << errors << " errors found." << std::endl; } return entries; } std::vector CSVReader::tokenise(std::string csvLine, char separator) { std::vector tokens; signed int start, end; std::string token; start = csvLine.find_first_not_of(separator, 0); do{ end = csvLine.find_first_of(separator, start); if (start == csvLine.length() || start == end) break; if (end >= 0) token = csvLine.substr(start, end - start); else token = csvLine.substr(start, csvLine.length() - start); tokens.push_back(token); start = end + 1; } while(end > 0); return tokens; } OrderBookEntry CSVReader::stringsToOBE(std::vector tokens) { double price, amount; if (tokens.size() != 5) // bad { //std::cout << "Bad line " << std::endl; throw std::exception{}; } // we have 5 tokens try { price = std::stod(tokens[3]); amount = std::stod(tokens[4]); } catch(const std::exception& e) { throw; } OrderBookEntry obe{price, amount, tokens[0], tokens[1], OrderBookEntry::stringToOrderBookType(tokens[2])}; return obe; }