This repository has been archived by the owner on Mar 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
csvreader.cpp
115 lines (101 loc) · 2.35 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
107
108
109
110
111
112
113
114
115
/**
* Dempster-Shafer Library for Evidence-Theory
* Thilo Michael, Jeffrey Jedele
* 2012
* > csv reader, implementation
*/
#include "csvreader.hpp"
using namespace std;
CSVReader::CSVReader(string filename) {
ifstream csvFile(filename.c_str());
string line, header;
if (csvFile.is_open()) {
//Get the first line of the file (header)
getline(csvFile, header);
//Check the length of the header
if (header.length() == 0) {
throw 1;
}
//Extract the header fields
int start = 0;
for (int i = 0; i < header.length(); i++) {
if (header[i] == ';') {
headers.push_back(header.substr(start, i-start));
start = i+1;
}
}
headers.push_back(header.substr(start, header.length()-1-start));
//Create the columns
vector<int> *dummy;
for (int i = 0; i < headers.size(); i++) {
dummy = new vector<int>();
columns.push_back(*dummy);
}
//Fill the columns
int counter;
while(csvFile.good()) {
getline(csvFile, line);
if (line.length() == 0)
break;
start = 0;
counter = 0;
for (int i = 0; i < line.length(); i++) {
if (line[i] == ';') {
columns.at(counter).push_back(atoi(line.substr(start,i-start).c_str()));
counter++;
start = i+1;
}
}
columns.at(counter).push_back(atoi(line.substr(start, line.length()-1-start).c_str()));
if (counter+1 != headers.size()) {
throw 2;
}
}
} else {
throw 3;
}
csvFile.close();
}
int CSVReader::number_of_columns() {
return headers.size();
}
int CSVReader::number_of_rows() {
return columns.at(0).size();
}
string CSVReader::header(int column) {
return headers.at(column);
}
int CSVReader::value(int row, int column) {
return columns.at(column).at(row);
}
int CSVReader::value(int row, string column) {
int index;
if ((index = header_index(column)) != -1)
return value(row, index);
else
throw 1;
}
vector<int> CSVReader::column(int column) {
return columns.at(column);
}
vector<int> CSVReader::column(string column) {
int index;
if ((index = header_index(column)) != -1)
return this->column(index);
else
throw 1;
}
vector<int> CSVReader::row(int row) {
vector<int> rowvec;
for (int i = 0; i < headers.size(); i++) {
rowvec.push_back(columns.at(i).at(row));
}
return rowvec;
}
int CSVReader::header_index(string name) {
for (int i = 0; i < headers.size(); i++) {
if (headers.at(i).compare(name) == 0)
return i;
}
return -1;
}