I have CSV data file contained follow info:
-0.2500000000,15, 15;15;15;15;15;15;15;15;15;15;15;15;15;15;15;15;15;0;0;0;0;0;15;0;0 ,0,0
I only want to add double quotes around those data with semi-colon between them. And I know a specific data that needs to add double quotes.
After add double quotes it should be like this.
-0.2500000000,15, "15;15;15;15;15;15;15;15;15;15;15;15;15;15;15;15;15;0;0;0;0;0;15;0;0" ,0,0
I need to add double quotes for each line of CSV data text line, re-write back to samefile or different. What I plan to do is, using boost token
typedef boost::tokenizer <boost::escaped_list_separator<char> > my_tokenizerDL;
while (getline(infile, line) && lineCount <= NumOfRecords)
{
for (my_tokenizerDL::iterator it(tok.begin()), end(tok.end()); it != end; ++it)
{
mystrDL.push_back(*it);
}
for (vector < string >::iterator _mit(mystrDL.begin()); _mit != mystrDL.end(); _mit++)
{
//get token position and add double quotes
//...........
//...........
}
}
////////////dump back to file/////////////////
If you have some advises, I appreciate for your opinions.
================================================================================= After Chad helped out, here are the whole codes which are working as what I need: Purpose: Read csv data txt file each line, then search for column which has ";" between them, and add double quotes around them. Finally, write it back to file. There is an extra "," at the end of each csv data line. I did not fix it!
ifstream infile("c:\\inputD.csv");
if (!infile)
return EXIT_FAILURE;
ofstream CSVToFile("c:\\TestCSV.csv", ios::out);
std::string line_from_file;
std::vector<std::string> split_line_to_file;
while (getline(infile, line_from_file))
{
boost::split(split_line_to_file, line_from_file, boost::is_any_of(","));
for(auto str = split_line_to_file.begin(), end = split_line_to_file.end();
str != end; ++str)
{
if(std::string::npos != str->find(';'))
(*str) = "\"" + (*str) + "\",";
else
(*str) = (*str) + ",";
CSVToFile << (*str);
std::cout<<*str;
if (*str == split_line_to_file.back())
break;
}
CSVToFile << ";"<<std::endl;
std::cout<<std::endl;
}
infile.close();
CSVToFile.close();
If you format is as simple as you describe, I'd use boost::split
given the string and the delimeter of ','. Then just put quotes around any string that contains a ;
.
Similar to this:
// warning: pseudo code...
std::string line_from_file;
std::vector<std::string> split_line_to_file;
boost::split(split_line_to_file, line_from_file, boost::is_any_of(","));
for(auto str = split_line_to_file.begin(), end = split_line_to_file.end();
str != end; ++str)
{
if(std::string::npos != str->find(';'))
(*str) = "\"" + (*str) + "\"";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.