-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSVReader.h
89 lines (75 loc) · 1.89 KB
/
CSVReader.h
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
/***** CSVReader.h *****/
// Built upon and inspired by:
// - https://github.com/abhinav1602/.csv-to-.cpp-2D-Array/blob/master/main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <ctype.h>
#include <stdlib.h>
#include <vector>
using namespace std;
// Function to get the number of rows of .csv file
int getSizeCSV(string filename){
string line;
// int i=0;
int sizeCSV = 0;
// string num = "";
// float arr[1000][10];
// std::vector<float> gData;
ifstream infile (filename);
if(infile.is_open())
{
while (getline(infile,line))
{
//increase row number for array
sizeCSV++;
}
// Remove first row (header) and get number of rows
sizeCSV -= 1;
//close the file
infile.close();
}
return sizeCSV;
}
// Function to get data from one collumn of the .csv file
std::vector<float> getDataCSV(string filename, int column){
string line;
int i=0, j=0, k=0, len = 0, last=0;
int SizeCSV = 0;
string num = "";
float arr[1000][10];
std::vector<float> gData;
ifstream infile (filename);
if(infile.is_open())
{
while (getline(infile,line) )
{
k=0,last=0,j=0;
len=line.length();
while(k!=len){
if(line[k]==','||k==len-1){
//for converting string into number
arr[i][j]=atof(num.append(line,last,k).c_str());
//Emtying string for getting next data
num="";
//increasing column number after saving data
j++;
if(k!=len-1)
last=k+1;
}
k++;
}
//increase row number for array
i++;
}
}
else cout << "Unable to open file";
// Remove first row (header) and get number of rows
SizeCSV = getSizeCSV(filename);
// Save values from column to global array
for(int x=0; x < SizeCSV; x++){
gData.push_back(arr[x+1][column]);
}
return gData;
}