C++ CSV line with commas and strings within double quotes(带有逗号和双引号内的字符串的 C++ CSV 行)
问题描述
我正在用 C++ 读取 CSV 文件,行格式如下:
I'm reading a CSV file in C++ and the row format is as such:
小学,中学,第三",主要",,中学",18, 4, 0, 0, 0
"Primary, Secondary, Third", "Primary", , "Secondary", 18, 4, 0, 0, 0
(注意空值)
当我这样做时:
while (std::getline(ss, csvElement, ',')) {
csvColumn.push_back(csvElement);
}
这会将第一个字符串分成不正确的部分.
This splits up the first string into pieces which isn't correct.
如何在迭代时保留字符串?我尝试将上述方法结合起来,同时还抓取了由双引号分隔的行,但我得到了疯狂的结果.
How do I preserve the string when iterating? I tried to do a combination of the above and while also grabbing the lines separated by double quote but I got wild results.
推荐答案
您需要根据是否在引号之间来解释逗号.这对于 getline() 来说太复杂了.
You need to interpret the comma depending on whether you're betwwen the quote or not. This is too complexfor getline().
解决方案是使用 getline() 读取整行,并通过逐个字符遍历字符串来解析该行,并维护一个指示符是否在双引号之间.
The solution would be to read the full line with getline(), and parse the line by iterating through the string character by character, and maintaing an indicator whether you're between double quotes or not.
这是第一个原始"示例(未删除字段中的双引号且不解释转义字符):
Here is a first "raw" example (double quotes are not removed in the fields and escape characters are not interpreted):
string line;
while (std::getline(cin, line)) { // read full line
const char *mystart=line.c_str(); // prepare to parse the line - start is position of begin of field
bool instring{false};
for (const char* p=mystart; *p; p++) { // iterate through the string
if (*p=='"') // toggle flag if we're btw double quote
instring = !instring;
else if (*p==',' && !instring) { // if comma OUTSIDE double quote
csvColumn.push_back(string(mystart,p-mystart)); // keep the field
mystart=p+1; // and start parsing next one
}
}
csvColumn.push_back(string(mystart)); // last field delimited by end of line instead of comma
}
在线演示
这篇关于带有逗号和双引号内的字符串的 C++ CSV 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有逗号和双引号内的字符串的 C++ CSV 行
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
