-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataRetriever.cpp
More file actions
88 lines (70 loc) · 2.05 KB
/
DataRetriever.cpp
File metadata and controls
88 lines (70 loc) · 2.05 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
#include "DataRetriever.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
void DataRetriever::retrieve_data(const std::string& path) {
std::ifstream file(path);
if (file.is_open()) {
handleFirstLine(file);
readInRestOfFile(file);
file.close();
}
else {
std::cerr << "Could not open file '" << path << "'" << std::endl;
// TODO: throw error that can be handled by the caller
}
}
void DataRetriever::handleFirstLine(std::ifstream& file) {
std::vector<std::string> cells = get_line_cells(file);
try {
double gdp = std::stod(cells[1]);
x.push_back(cells[0]);
y.push_back(gdp);
}
catch (std::invalid_argument ia) {
// line was title
}
}
void DataRetriever::readInRestOfFile(std::ifstream& file) {
while (!file.eof()) {
std::vector<std::string> cells = get_line_cells(file);
if (cells.empty()) {
break;
}
x.push_back(cells[0]);
y.push_back(std::stod(cells[1]));
// TODO: Handle exceptions thrown by stod
}
}
std::vector<std::string> DataRetriever::getX() {
return x;
}
std::vector<double> DataRetriever::getY() {
return y;
}
QDateTime DataRetriever::stringToDate(const std::string& string) {
int year = 0, month = 0, day = 0;
QRegularExpression re("(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)");
auto match = re.match(QString::fromStdString(string));
year = match.captured(1).toInt();
month = match.captured(2).toInt();
day = match.captured(3).toInt();
QDateTime date;
date.setDate(QDate(year, month, day));
return date;
}
std::vector<std::string> DataRetriever::get_line_cells(std::istream& input) {
std::vector<std::string> cells;
std::string line;
std::getline(input, line);
std::stringstream linestream(line);
std::string cell;
while (std::getline(linestream, cell, ',')) {
cells.push_back(cell);
}
return cells;
}