-7

I have a CSV file. For eg,

field1,field2,field3,field4

I am parsing the file using getline and ',' as delimiter. The problem is when one of the fields itself contain a ',' then parsing leads to incorrect results.

So, I would like to escape ',' that is present within any field while writing the CSV file. Since there is no special escape character for ',' as for '\n', I have no clue on how to do this. Please help me.

  • 3
    This has **nothing** to do with escape characters in C++. **You** are parsing the CSV, not the C++ compiler, right? So **you** invent some escape syntax for the comma, which then you implement in your CSV parser. – The Paramagnetic Croissant Jan 09 '15 at 06:36
  • Here are some ways shown, how to solve such kind of problems: [Why does reading a struct record fields from std::istream fail, and how can I fix it?](http://stackoverflow.com/questions/23047052/why-does-reading-a-struct-record-fields-from-stdistream-fail-and-how-can-i-fi) – πάντα ῥεῖ Jan 09 '15 at 08:52

2 Answers2

0

You can't escape commas, all you can do is that parse the field before writing and change commas to some other character, while reading change that character to commas. Or you can go for some other file formats than csv.

Venkatesh
  • 1,537
  • 15
  • 28
0

I had the same problem. Simply double quote the string you want to write.

CHAR szTempString[2048] = {0};
strcpy(szTempString, "\"");

strcat(szTempString, szInput);
strcat(szTempString, "\"");

Now write that szTempString to your CSV file.

Tushar
  • 3
  • 4