chester
chester

Reputation: 1

Getline function is not parsing end of line in CSV file

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?

Upvotes: 0

Views: 128

Answers (1)

john
john

Reputation: 87959

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

Upvotes: 1

Related Questions