I'm reading a CSV file in C++ and the row format is as such:
"Primary, Secondary, Third", "Primary", , "Secondary", 18, 4, 0, 0, 0
(notice the empty value)
When I do:
while (std::getline(ss, csvElement, ',')) {
csvColumn.push_back(csvElement);
}
This splits up the first string into pieces which isn't correct.
How do I preserve the string when iterating? I tried to do a combination of the above and while also grabbing the lines separated by double quote but I got wild results.
You need to interpret the comma depending on whether you're betwwen the quote or not. This is too complexfor getline()
.
The solution would be to read the full line with getline()
, and parse the line by iterating through the string character by character, and maintaing an indicator whether you're between double quotes or not.
Here is a first "raw" example (double quotes are not removed in the fields and escape characters are not interpreted):
string line;
while (std::getline(cin, line)) { // read full line
const char *mystart=line.c_str(); // prepare to parse the line - start is position of begin of field
bool instring{false};
for (const char* p=mystart; *p; p++) { // iterate through the string
if (*p=='"') // toggle flag if we're btw double quote
instring = !instring;
else if (*p==',' && !instring) { // if comma OUTSIDE double quote
csvColumn.push_back(string(mystart,p-mystart)); // keep the field
mystart=p+1; // and start parsing next one
}
}
csvColumn.push_back(string(mystart)); // last field delimited by end of line instead of comma
}