Std :: getline for comma delimited table file with quotes around specific fields

I mainly use the following code. This code goes line by line and captures different fields of the shared comma-separated table file. My problem is that sometimes the "title" field can contain commas. When this happens, it is surrounded by quotation marks: "This is my title." But when my code sees the comma, it just treats everything after it as the next field. Not all names have quotes around them, only those who have commas. My problem is that I have no idea how to do code verification for this .... How can I get my code to verify this problem?

Thanks a lot, yall. It means a lot to my paid work!

while (getline(BookLine, ImpLine, '\n')) // Get each line { // create a string stream from the standard string std::istringstream StrLine(ImpLine); std::string bookNumber, chk, author, title, edition; // Parse lines std::getline(StrLine,bookNumber,','); std::getline(StrLine,chk,','); std::getline(StrLine,author,','); std::getline(StrLine,title,','); std::getline(StrLine,edition,','); } 
+4
source share
2 answers

The completion of this well is quite difficult. Basically, you read the first character. If this is not a quote, you read the next comma. If this is a quote, you read the following quote. Then you look at the next character and see if there is another quote. If so, you read the next quote again and add what you read at the end of what you read for the first time, but without one of the quotes (i.e. the Quote in the quoted line is represented by two consecutive quotes). When you get a quote followed by something other than a quote (usually a comma), you reach the end of this field.

+6
source

Not tested, but rudely you want ...

 std::vector<string> values; std::string value; bool in_quoted = false; for (const char* p = ImpLine.c_str(); *p; ++p) if (*p == ',' && !in_quoted) { values.push_back(value); value.clear(); } else if (*p == '"') if (in_quoted) if (p[1] == '"') value += *++p; else in_quoted = false; else in_quoted = true; else value += *p; values.push_back(value); 

(You can adjust it to crop the margins of the surrounding space.)

+1
source

All Articles