简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM