initial project setup
This commit is contained in:
68
stdlib/csvparser.cpp
Normal file
68
stdlib/csvparser.cpp
Normal file
@@ -0,0 +1,68 @@
|
||||
|
||||
#include "csvparser.h"
|
||||
|
||||
|
||||
CsvParser::CsvParser(bool skip_hdr, char field_sep, char quote_ch, char line_sep, char line_sep2) {
|
||||
skip_header = skip_hdr;
|
||||
field_separator = field_sep;
|
||||
quote_character = quote_ch;
|
||||
line_separator = line_sep;
|
||||
line_separator2 = line_sep2;
|
||||
|
||||
header_skiped = false;
|
||||
}
|
||||
|
||||
void CsvParser::parseCSV(const std::string &csvSource, std::vector< std::vector<std::string> > &lines) {
|
||||
bool inQuote(false);
|
||||
bool newLine(false);
|
||||
std::string field;
|
||||
lines.clear();
|
||||
std::vector<std::string> line;
|
||||
|
||||
std::string::const_iterator aChar = csvSource.begin();
|
||||
while (aChar != csvSource.end()) {
|
||||
if (*aChar == quote_character) {
|
||||
newLine = false;
|
||||
inQuote = !inQuote;
|
||||
} else if (*aChar == field_separator) {
|
||||
newLine = false;
|
||||
if (inQuote == true) {
|
||||
field += *aChar;
|
||||
} else {
|
||||
line.push_back(field);
|
||||
field.clear();
|
||||
}
|
||||
} else if (*aChar == line_separator || *aChar == line_separator2) {
|
||||
if (inQuote == true) {
|
||||
field += *aChar;
|
||||
} else {
|
||||
if (newLine == false) {
|
||||
line.push_back(field);
|
||||
addLine(line, lines);
|
||||
field.clear();
|
||||
line.clear();
|
||||
newLine = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newLine = false;
|
||||
field.push_back(*aChar);
|
||||
}
|
||||
|
||||
aChar++;
|
||||
}
|
||||
|
||||
if (field.size())
|
||||
line.push_back(field);
|
||||
|
||||
addLine(line, lines);
|
||||
}
|
||||
|
||||
void CsvParser::addLine(const std::vector<std::string> &line, std::vector< std::vector<std::string> > &lines) {
|
||||
if (skip_header && !header_skiped) {
|
||||
header_skiped = true;
|
||||
} else {
|
||||
if (line.size())
|
||||
lines.push_back(line);
|
||||
}
|
||||
}
|
||||
23
stdlib/csvparser.h
Normal file
23
stdlib/csvparser.h
Normal file
@@ -0,0 +1,23 @@
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class CsvParser {
|
||||
|
||||
private:
|
||||
char field_separator;
|
||||
char line_separator;
|
||||
char line_separator2;
|
||||
char quote_character;
|
||||
|
||||
bool skip_header;
|
||||
bool header_skiped;
|
||||
|
||||
public:
|
||||
CsvParser(bool skip_hdr = false, char field_sep = ',', char quote_ch = '"', char line_sep = '\r', char line_sep2 = '\n');
|
||||
|
||||
void parseCSV(const std::string &csvSource, std::vector< std::vector<std::string> > &lines);
|
||||
|
||||
private:
|
||||
void addLine(const std::vector<std::string> &line, std::vector< std::vector<std::string> > &lines);
|
||||
};
|
||||
Reference in New Issue
Block a user