C ++ Boost读取CSV数据并将双引号添加到某些列,然后重新写回文件

时间:2011-09-01 14:32:05

标签: c++ boost

我的CSV数据文件包含以下信息:

  

-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

我只想在这些数据周围添加双引号,并在它们之间使用分号。我知道需要添加双引号的特定数据。

添加双引号后应该是这样的。

  

-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

我需要为每行CSV数据文本行添加双引号,重新写回同一文件或不同。我打算做的是使用提升令牌

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/////////////////

如果您有一些建议,我感谢您的意见。

============================================ ===================================== 在Chad帮忙之后,以下是我需要的整个代码: 目的:每行读取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();

1 个答案:

答案 0 :(得分:3)

如果您的格式与您描述的一样简单,我会使用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) + "\"";
}
相关问题