0

I am simply trying to read a CSV file and print it on the terminal, but I think the getLine() function is not parsing the end of line character. I thought that it was because the file that I was reading was created on Windows and I was running the script on Linux. To test that theory, I created a new CSV file on Linux, but it is having the same issue.

CSV File:

julio,tito,monroy
felipe,aguilar,jowell
readCsv.open("test.csv", ios::in);
if(readCsv.is_open()){
    string time;
    string in;
    string out;
    int count = 1;

    while(!readCsv.eof()){
        getline(readCsv, time, ',');
        getline(readCsv, in, ',');
        getline(readCsv, out, ',');

        printf("%d : %s %s %s", count, time.c_str(), in.c_str(), out.c_str());

        count++;
    }

} else {
    printf("There was an error when trying to open the csv file. \n");
}

What am I doing wrong?

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
  • 1
    To read a CSV file, see [this](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c) – NathanOliver Aug 15 '19 at 20:15
  • 1
    I suggest a change of strategy. 1. Read the contents of the file line by line. 2. Process each line using a `std::istringstream`. – R Sahu Aug 15 '19 at 20:23

1 Answers1

1

Like this

while (getline(readCsv, time, ',') &&
        getline(readCsv, in, ',') &&
        getline(readCsv, out))
{

There are two things wrong with your version. Firstly your third column is terminated by an end of line, not by a comma, so getline(readCsv, out, ',') is wrong. Secondly your understanding of how eof works is incorrect, see here

john
  • 85,011
  • 4
  • 57
  • 81