-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCSVReader.cpp
More file actions
89 lines (79 loc) · 2.23 KB
/
Copy pathCSVReader.cpp
File metadata and controls
89 lines (79 loc) · 2.23 KB
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
#include "CSVReader.h"
#include "OrderBookEntry.h"
#include <exception>
#include <fstream>
#include <iostream>
#include <vector>
using namespace ::std;
CSVReader::CSVReader() {}
vector<OrderBookEntry> CSVReader::readCSV(string csvFileName) {
vector<OrderBookEntry> entries;
ifstream csvFile{csvFileName};
string line;
if (!csvFile.is_open()) {
throw runtime_error("Could not open file");
}
while (getline(csvFile, line)) {
try {
vector<string> tokens = tokenize(line, ',');
OrderBookEntry obe = stringToOBE(tokens);
entries.push_back(obe);
} catch (const exception &e) {
}
}
csvFile.close();
cout << "Read " << entries.size() << " entries from file "
<< csvFileName << endl;
return entries;
}
vector<string> CSVReader::tokenize(string line, char separator) {
vector<string> tokens;
signed int start, end;
string token;
start = line.find_first_not_of(separator, 0);
do {
end = line.find_first_of(separator, start);
if (start == line.length() || start == end)
break;
if (end >= 0)
token = line.substr(start, end - start);
else
token = line.substr(start, line.length() - start);
tokens.push_back(token);
start = end + 1;
} while (end > 0);
return tokens;
}
OrderBookEntry CSVReader::stringToOBE(vector<string> tokens) {
double price, amount;
if (tokens.size() != 5) {
cout << "bad line " << endl;
throw exception{};
}
try {
price = stod(tokens[3]);
amount = stod(tokens[4]);
} catch (const exception &e) {
cout << "bad line";
throw;
}
OrderBookEntry obe{price, amount, tokens[0], tokens[1],
OrderBookEntry::stringToOrderBookType(tokens[2])};
return obe;
}
OrderBookEntry CSVReader::stringToOBE(string priceString, string amountString,
string timestamp, string product,
OrderBookType orderType)
{
double price, amount;
try {
price = stod(priceString);
amount = stod(amountString);
} catch (const exception &e) {
cout << "bad float: " << priceString << endl;
cout << "bad float: " << amountString << endl;
throw;
}
OrderBookEntry obe {price,amount,timestamp,product,orderType};
return obe;
}