[英]C++ Boost Read CSV data and add double quotes to certain columns then re-write back to file
我有包含以下信息的CSV数据文件:
-0.2500000000,15,15; 15; 15; 15; 15; 15; 15; 15; 15; 15; 15; 15; 15; 15; 15; 15; 15; 15; 0; 0; 0; 0; 15 ; 0; 0,0,0
我只想在这些数据之间添加双引号,并在它们之间使用分号。 而且我知道需要添加双引号的特定数据。
添加双引号后,应该是这样。
-0.2500000000,15, “ 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
我需要为CSV数据文本行的每行添加双引号,然后重新写回相同文件或不同文件。 我打算做的是使用Boost令牌
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/////////////////
如果您有任何建议,我感谢您的意见。
================================================== =============================在乍得帮忙之后,下面是符合我需要的全部代码:目的:每行读取csv数据txt文件,然后搜索具有“;”的列 在它们之间添加双引号。 最后,将其写回到文件中。 每个csv数据行的末尾都有一个额外的“,”。 我没有解决!
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();
如果您格式化的过程像您描述的那样简单,我将使用boost::split
给出字符串和','的分隔符。 然后只要在任何包含;
字符串周围加上引号即可;
。
与此类似:
// 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) + "\"";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.