-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSVReader.cpp
106 lines (95 loc) · 3.08 KB
/
CSVReader.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include "CSVReader.h"
// #include "OrderBookEntry.h"
#include <iostream>
#include <fstream>
// #include <string>
// #include <vector>
CSVReader::CSVReader(){}
std::vector<std::string> CSVReader::tokenise(std::string csvLine, char separator){
std::vector<std::string> tokens;
int start;
int 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 != std::string::npos);
return tokens;
};
std::vector<OrderBookEntry> CSVReader::readCSV(std::string csvFileName){
std::vector<OrderBookEntry> data;
std::vector<std::string> tokens;
std::ifstream csvFile{csvFileName};
std::string line;
if (csvFile.is_open()){
std::cout << "File Opened Successfully" << std::endl;
while(std::getline(csvFile, line)){
try{
tokens = tokenise(line, ',');
OrderBookEntry obe = strings2OrderBookEntry(tokens);
data.push_back(obe);
}catch(const std::exception& e){
std::cout << "Bad Data. " << std::endl;
}
}
csvFile.close();
}else{
std::cout << "File opening failed " << std::endl;
}
return data;
};
OrderBookEntry CSVReader::strings2OrderBookEntry(std::vector<std::string> tokens){
double price;
double amount;
if (tokens.size() != 5){
std::cout << "CSVReader::strings2OrderBookEntry, Bad Data: " << std::endl;
throw std::exception{};
}else{
try{
price = std::stod(tokens[3]);
amount = std::stod(tokens[4]);
} catch(const std::exception& e){
std::cout << "CSVReader::strings2OrderBookEntry, Bad Value: "<< std::endl;
throw;
}
}
OrderBookEntry obe{price,
amount,
tokens[0],
tokens[1],
OrderBookEntry::string2orderBookType(tokens[2])
};
return obe;
};
OrderBookEntry CSVReader::strings2OrderBookEntry(std::string priceString,
std::string amountString,
std::string timestamp,
std::string product,
OrderBookType order_type){
double price;
double amount;
try{
price = std::stod(priceString);
amount = std::stod(amountString);
} catch(const std::exception& e){
std::cout << "CSVReader::strings2OrderBookEntry, Bad Value: "<< std::endl;
throw;
}
OrderBookEntry obe{price,
amount,
timestamp,
product,
order_type
};
return obe;
};