0% found this document useful (0 votes)
21 views2 pages

Parse CSV File

Parse a CSV file on the fly in C/C++.

Uploaded by

john smith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views2 pages

Parse CSV File

Parse a CSV file on the fly in C/C++.

Uploaded by

john smith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

// parse a csv file on the fly

// compile with g++ -std=c++11 csv.cpp -o csv


// http://www.wtfpl.net/

#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>

void parseCsv(const std::string &path,


std::vector<std::vector<double>> &destination)
{
std::ifstream in(path);
std::string line;
std::string buf;
std::stringstream field;
double value;
while (std::getline(in, line))
{
std::vector<double> entry;

std::size_t pos;
while ((pos = line.find(',')) != std::string::npos)
{
buf = line.substr(0, pos);
buf.erase(std::remove(buf.begin(), buf.end(), 'c'), buf.end());
field.str(buf);
field >> value;
field.clear();
entry.push_back(value);
line = line.substr(pos + 1);
}

// This is the last entry in this line, simply read it ignoring


// whitespace.
field.str(line);
field >> value;
field.clear();
entry.push_back(value);

if (!entry.empty())
{
destination.push_back(entry);
}
}
in.close();
}

int main(int, char **)


{
std::vector<std::vector<double>> data;
parseCsv("data.csv", data);
for (const auto &line : data)
{
for (const auto &value : line)
{
std::cout << value << " ";
}
std::cout << std::endl;
}
}

You might also like