C++ Reading Csv File

I want to read csv file by using c++ so here is my code

 int main(){
 ifstream classFile("class.csv");
 vector<string> classData;

 while (getline(classFile, line,',')) // there is input overload classfile
        {
            classData.push_back(line);  

        }
}

here is my question : my problem is when it reads the last column of each row (since it is not separated by comma) it reads last column data and first of next row data for example if my data was like

className, classLocation, Professor c++, Library, John

then it reads like className/ classLocation/ Professor c++/ Library / John

is there anyway that I can separate my last column from first of next row? Thank you and sorry that it is confusing

3

3 Answers

Read the file line by line:

std::string line;
while(std::getline(stream, line)) ...

Pass each line to a istingstream and read the fields:

std::istringstream s(line);
std::string field;
while (getline(s, field,',')) ...

Disclaimer: This is a simplified parsing of a csv-file.

3

Sorry, can I shove in some plain C into this thread?

Reading csv is pretty clear there:

#include <stdio.h>


int main()
{
  float f1, f2;

  FILE *fp;
  fp = fopen("file.csv", "r");

  while (fscanf(fp, "%g,%g\n", &f1, &f2) == 2)
    printf("%g\n", f1+f2);
}

And quite certainly it should work where C++ works.

There, in the while, we check how many objects fscanf has found: fscanf(fp, "%g,%g\n", &f1, &f2) == 2 -- fscanf returns number of objects it finds.

I hope it might be of help to someone.

(And if anybody would like to see more info on fscanf and reading files -- leave some comments.)

2

In case you are interested to have a void function to be called in your main section, please take a look at the following code:

void readCSV(const string &strPath2Dataset)
{   
    ifstream csvFile;
    string strPathCSVFile = strPath2Dataset + "/test.csv";
    csvFile.open(strPathCSVFile.c_str());

    if (!csvFile.is_open())
    {
        cout << "Path Wrong!!!!" << endl;
        exit(EXIT_FAILURE);
    }

    vector<long double> timeStampIMU;
    vector<long double> gyro_X;
    vector<long double> gyro_Y;
    vector<long double> gyro_Z;

    vector<long double> acc_X;
    vector<long double> acc_Y;
    vector<long double> acc_Z;

    string line;
    vector <string> vec;
    getline(csvFile, line); // skip the 1st line

    while (getline(csvFile,line))
    {
        if (line.empty()) // skip empty lines:
        {
            //cout << "empty line!" << endl;
            continue;
        }

        istringstream iss(line);
        string lineStream;
        string::size_type sz;

        vector <long double> row;

        while (getline(iss, lineStream, ','))
        {  
            row.push_back(stold(lineStream,&sz)); // convert to double
        }

        timeStampIMU.push_back(row[0]);

        gyro_X.push_back(row[1]);
        gyro_Y.push_back(row[2]);
        gyro_Z.push_back(row[3]);

        acc_X.push_back(row[4]);
        acc_Y.push_back(row[5]);
        acc_Z.push_back(row[6]);
    }

    //cout << "size ts = " << timeStampIMU.size() << endl;
    for (size_t i = 0; i < timeStampIMU.size(); i++)
    {
        cout << "ts_imu = " << setprecision(12) << timeStampIMU[i] << endl;

        cout << "gx = " << setprecision(12) << gyro_X[i] << endl;
        cout << "gy = " << setprecision(12) << gyro_Y[i] << endl;
        cout << "gz = " << setprecision(12) << gyro_Z[i] << endl;

        cout << "ax = " << setprecision(12) << acc_X[i] << endl;
        cout << "ay = " << setprecision(12) << acc_Y[i] << endl;
        cout << "az = " << setprecision(12) << acc_Z[i] << endl;
        cout << "--------------------------------" << endl;
    }
}

My .csv file is dataset provided from IMU sensor, separated by comma:

TimeStamp, Gyro_X, Gyro_Y, Gyro_Z, Acc_X, Acc_Y, Acc_Z

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest