Repository navigation
Expand file tree
/
Copy pathCSVParser.cpp
More file actions
96 lines (87 loc) · 1.62 KB
/
Copy pathCSVParser.cpp
File metadata and controls
96 lines (87 loc) · 1.62 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
90
91
92
93
94
95
96
/**
* CSV Parser for C++
*
* Adapted from: http://www.zedwood.com/article/cpp-csv-parser
*/
#include "CSVParser.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <istream>
CSVParser::CSVParser(const char *filename) : in(filename)
{
delimiter = ',';
}
CSVParser::CSVParser(const char *filename, char delim) : in(filename), delimiter(delim)
{
}
bool CSVParser::good()
{
return in.good();
}
bool CSVParser::fail()
{
return in.fail();
}
void CSVParser::skip()
{
char f[256];
in.getline(f, 256);
}
void CSVParser::skip(int count)
{
char f[256];
for (int i = 0; i < count; ++i)
{
in.getline(f, 256);
}
}
std::vector<std::string> CSVParser::next()
{
std::stringstream ss;
bool inquotes = false;
std::vector<std::string> row;
while(in.good())
{
char c = in.get();
if (!inquotes && c=='"')
{
inquotes=true;
}
else if (inquotes && c=='"')
{
if ( in.peek() == '"')
{
ss << (char)in.get();
}
else
{
inquotes=false;
}
}
else if (!inquotes && c==delimiter)
{
row.push_back( ss.str() );
ss.str("");
}
else if (!inquotes && (c=='\r' || c=='\n') )
{
if(in.peek()=='\n') { in.get(); }
row.push_back( ss.str() );
return row;
}
else
{
ss << c;
}
}
std::vector<std::string> a;
return a;
}
CSVParser::~CSVParser()
{
if(!in.fail())
in.close();
}