将csv文件的一行拆分为std :: vector? [英] Splitting a line of a csv file into a std::vector?

查看:131
本文介绍了将csv文件的一行拆分为std :: vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个逐行读取CSV文件的函数。对于每一行,它将把行拆分成一个向量。这样做的代码是

I have a function that will read a CSV file line by line. For each line, it will split the line into a vector. The code to do this is

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

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

除了读取最后一个值为空的行。例如,

This works fine except for if it reads a line where the last value is blank. For example,

text1,tex2,

我想要返回一个大小为3的向量,其中第三个值是空的。但是,它只是返回一个大小为2的向量。我如何更正这个?

I would want this to return a vector of size 3 where the third value is just empty. However, instead it just returns a vector of size 2. How can I correct this?

推荐答案

bool addEmptyLine = sText.back() == ',';

/* your code here */

if (addEmptyLine) m_vecFields.push_back("");

sText += ',';     // text1, text2,,

/* your code */

assert(m_vecFields.size() == 3);

这篇关于将csv文件的一行拆分为std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆