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

后端 未结 3 1064
臣服心动
臣服心动 2020-12-07 03:05

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 v

3条回答
  •  有刺的猬
    2020-12-07 03:21

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

    #include 
    #include 
    #include 
    #include 
    
    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 << "\n";
        }
    }
    

    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.

提交回复
热议问题