带有逗号和双引号内的字符串的C ++ CSV行 [英] C++ CSV line with commas and strings within double quotes

查看:127
本文介绍了带有逗号和双引号内的字符串的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行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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