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 行
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
