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

标签 c++ csv vector std

我有一个函数可以逐行读取 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/

相关文章:

c++ - 如何使用 X11 避免图形绘图中的闪烁

c++ - 在成员变量中存储 std::to_string(x).c_str() 会产生垃圾

c++ - 为什么这个库 dlopen 顺序很重要?

c++ - 在 llvm 中位转换后 vector 的位布局

Java - 深度克隆具有多种类型元素的 Vector

c++ - 如何将json文件读入C++字符串

python - 使用 python 和 psycopg2 将 CSV 导入 postgres 时出错

python - 如何使用 python 和 pandas 将单个 `"` 放入我的 csv 中

python - 列数据内的分隔符问题

C++试图从文件中读取数据到 vector 中