gpt4 book ai didi

c++ - 将 csv 文件的一行拆分为 std::vector?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:07:47 25 4
gpt4 key购买 nike

我有一个函数可以逐行读取 CSV 文件。对于每一行,它会将行拆分为一个 vector 。执行此操作的代码是

    std::stringstream ss(sText);
std::string item;

while(std::getline(ss, item, ','))
{
m_vecFields.push_back(item);
}

这工作正常,除非它读取最后一个值为空白的行。例如,

text1,tex2,

我希望它返回一个大小为 3 的 vector ,其中第三个值只是空的。但是,它只返回一个大小为 2 的 vector 。我该如何更正此问题?

最佳答案

您可以使用 boost::split 为您完成这一切。
http://www.boost.org/doc/libs/1_50_0/doc/html/string_algo/usage.html#id3207193

它在一行中具有您需要的行为。

示例 boost::split 代码

#include <iostream>
#include <vector>
#include <boost/algorithm/string.hpp>

using namespace std;

int main()
{
vector<string> strs;

boost::split(strs, "please split,this,csv,,line,", boost::is_any_of(","));

for ( vector<string>::iterator it = strs.begin(); it < strs.end(); it++ )
cout << "\"" << *it << "\"" << endl;

return 0;
}

结果

"please split"
"this"
"csv"
""
"line"
""

关于c++ - 将 csv 文件的一行拆分为 std::vector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11310947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com