Splitting a line of a csv file into a std::vector?(将一行 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将一行 csv 文件拆分为 std::vector?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
