How can I read and parse CSV files in C++?

https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c

If you don't care about escaping comma and newline, AND you can't embed comma and newline in quotes (If you can't escape then...) then its only about three lines of code (OK 14 ->But its only 15 to read the whole file).

std::vector<std::string> getNextLineAndSplitIntoTokens(std::istream& str)
{
    std::vector<std::string>   result;
    std::string                line;
    std::getline(str,line);

    std::stringstream          lineStream(line);
    std::string                cell;

    while(std::getline(lineStream,cell, ','))
    {
        result.push_back(cell);
    }
    // This checks for a trailing comma with no data after it.
    if (!lineStream && cell.empty())
    {
        // If there was a trailing comma then add an empty element.
        result.push_back("");
    }
    return result;
}

I would just create a class representing a row. Then stream into that object:

But with a little work we could technically create an iterator:

Now that we are in 2020 lets add a CSVRange object:

Last updated