-3

I have a csv file with the pattern:

firstname, lastname, id
angelina, jolie, 247 
... and so on...

I want to store the values in a Student class, but the problem is that it takes the last word of the first line and it concatenate with the first word of the second line(idangelina).The list has 5000 students to store in a Student array and I don't know how to separate them. The function is this:

int readFromCsv(string filePath, Student v[]){
    string line;
    ifstream csvfile;
    csvfile.open(filePath);
    int i = 0;
    while ( !csvfile.eof() ){//loops until the end of the file
        getline(csvfile, line, ',');//read a string until the next comma
        v[i].setFirstName(line); //set each student
        getline(csvfile, line, ',');
        v[i].setLastName(line);
        getline(csvfile, line, ',');
        v[i].setId(line);
        i += 1;
    }
    csvfile.close();
    return i;
}
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • If you can't use `std::vector`, you need to pass the size of `v` so that the code won't go out of bounds. – crashmstr May 14 '15 at 19:17
  • I am using i to return the size of the array, knowing that each line represents a student.The problem is how to separate the student id with the next name. – Eugen Eugen May 14 '15 at 19:20
  • See if this helps: http://stackoverflow.com/questions/23047052/why-does-reading-a-struct-record-fields-from-stdistream-fail-and-how-can-i-fi – πάντα ῥεῖ May 14 '15 at 19:20
  • @EugenEugen no, you are returning how many elements *you've written values to*, not the size of the array. The caller determines how big `v` is, and the file could have more than the caller has allocated! This is why we use `std::vector`. – crashmstr May 14 '15 at 19:22
  • 1
    You can see complete examples in http://stackoverflow.com/questions/12911299/read-csv-file-in-c. – Mihai8 May 14 '15 at 19:25
  • 1
    See also: [why eof is bad practice](http://stackoverflow.com/questions/5837639/eof-bad-practice) – Thomas Matthews May 14 '15 at 19:30

2 Answers2

1

For the last field in one line you should use

getline(csvfile, line);
v[i].setId(line);

instead of

getline(csvfile, line, ',');
v[i].setId(line);

because for the last field you don't want to read until the next comma but until the end of the line.

bweber
  • 3,772
  • 3
  • 32
  • 57
0

, does not separate one record's ID from the next record's first name, so you cannot use it as a delimiter for that column.

Also you need to put a limit on how many records you can read, otherwise you risk overrunning v if the file has too many records.