Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 views
in Technique[技术] by (71.8m points)

C++ CSV line with commas and strings within double quotes

I'm reading a CSV file in C++ and the row format is as such:

"Primary, Secondary, Third", "Primary", , "Secondary", 18, 4, 0, 0, 0

(notice the empty value)

When I do:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using std::quoted allows you to read quoted strings from input streams.

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::stringstream ss;
    ss << ""Primary, Secondary, Third", "Primary", , "Secondary", 18, 4, 0, 0, 0";

    while (ss >> std::ws) {
        std::string csvElement;

        if (ss.peek() == '"') {
            ss >> std::quoted(csvElement);
            std::string discard;
            std::getline(ss, discard, ',');
        }
        else {
            std::getline(ss, csvElement, ',');
        }

        std::cout << csvElement << "
";
    }
}

Live Example

The caveat is that quoted strings are only extracted if the first non-whitespace character of a value is a double-quote. Additionally, any characters after the quoted strings will be discarded up until the next comma.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...