[英]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.