-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSVParser.cpp
105 lines (92 loc) · 2.4 KB
/
CSVParser.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
#include "CSVParser.h"
CSVParser::CSVParser(){}
bool CSVParser::ParseCSV(istream& inpStr){
int result(0);
bool inQuote(false);
bool newLine(false);
string field;
this->lines.clear();
vector<string> line;
string csv = "";
string cell;
while(std::getline(inpStr,cell)){
csv += cell + "\n";
}
string::const_iterator aChar = csv.begin();
while (aChar != csv.end()){
switch (*aChar){
case '"':
newLine = false;
inQuote = !inQuote;
field += *aChar;
break;
case ',':
newLine = false;
if (inQuote == true)
field += *aChar;
else{
line.push_back(field);
field.clear();
}
break;
case '\n':
case '\r':
if (inQuote == true)
field += *aChar;
else{
if (newLine == false){
line.push_back(field);
this->lines.push_back(line);
field.clear();
line.clear();
newLine = true;
}
}
break;
default:
newLine = false;
field.push_back(*aChar);
break;
}
aChar++;
}
if (line.size()){
if (field.size())
line.push_back(field);
lines.push_back(line);
}
return result;
}
void CSVParser::TokenizeText(istream& inpStr){
//int result(0);
string field;
this->lines.clear();
vector<string> line;
string csv = "";
string cell;
while(std::getline(inpStr,cell)){
csv += cell + "\n";
}
string::const_iterator aChar = csv.begin();
while (aChar != csv.end()){
if (isspace(*aChar) || ispunct(*aChar)){
if (field.size() > 0){
line.push_back(field);
this->lines.push_back(line);
field.clear();
line.clear();
}
} else{
field.push_back(*aChar);
}
aChar++;
}
}
vector<string> CSVParser::GetNextLine(){
vector<string> tmp = this->lines.back();
this->lines.pop_back();
return tmp;
}
bool CSVParser::AtEnd(){
return this->lines.empty();
}