Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read CSV file in to vector in C++

Tags:

c++

csv

vector

nms

I'm doing the project that convert the python code to C++, for better performance. That python project name is Adcvanced EAST, for now, I got the input data for nms function, in .csv file like this:

"[ 5.9358170e-04  5.2773970e-01  5.0061589e-01 -1.3098677e+00
 -2.7747922e+00  1.5079222e+00 -3.4586751e+00]","[ 3.8175487e-05  6.3440394e-01  7.0218205e-01 -1.5393494e+00
 -5.1545496e+00  4.2795391e+00 -3.4941311e+00]","[ 4.6003381e-05  5.9677261e-01  6.6983813e-01 -1.6515008e+00
 -5.1606908e+00  5.2009044e+00 -3.0518508e+00]","[ 5.5172237e-05  5.8421570e-01  5.9929764e-01 -1.8425952e+00
 -5.2444854e+00  4.5013981e+00 -2.7876694e+00]","[ 5.2929961e-05  5.4777789e-01  6.4851379e-01 -1.3151239e+00
 -5.1559062e+00  5.2229333e+00 -2.4008298e+00]","[ 8.0250458e-05  6.1284608e-01  6.1014801e-01 -1.8556541e+00
 -5.0002270e+00  5.2796564e+00 -2.2154367e+00]","[ 8.1256607e-05  6.1321974e-01  5.9887391e-01 -2.2241254e+00
 -4.7920742e+00  5.4237065e+00 -2.2534993e+00]

one unit is 7 numbers, but a '\n' after first four numbers, I wanna read this csv file into my C++ project, so that I can do the math work in C++, make it more fast.

using namespace std;

void read_csv(const string &filename)
{
//File pointer
fstream fin;
//open an existing file
fin.open(filename, ios::in);

vector<vector<vector<double>>> predict;

string line;
while (getline(fin, line))
{
    std::istringstream sin(line);
    vector<double> preds;
    double pred;
    while (getline(sin, pred, ']'))
    {
        preds.push_back(preds);
    }

}

}

For now...my code emmmmmm not working ofc, I'm totally have no idea with this... please help me with read the csv data into my code. thanks

like image 627
BAO TONG Avatar asked Oct 22 '25 12:10

BAO TONG


1 Answers

Unfortunately parsing strings (and consequently files) is very tedious in C++.

I highly recommend using a library, ideally a header-only one, like this one.

If you insist on writing it yourself, maybe you can draw some inspiration from this StackOverflow question on how to parse general CSV files in C++.

like image 117
Benno Straub Avatar answered Oct 24 '25 03:10

Benno Straub