why is my code only getting me the first group of data from the file
(c++)
Records employee; vector<Records> recordlist; getline(datafile,employee.name); datafile >> employee.hours >> employee.rate >> employee.age; datafile.ignore(); while (datafile) { cout << "Name: " << employee.name << endl; cout << "Hours worked: " << employee.hours << endl; cout << "Rate of pay: " << employee.rate << endl; cout << "Age: " << employee.age << endl; recordlist.push_back(employee); getline(datafile,employee.name); datafile >> employee.hours >> employee.rate >> employee.age; datafile.ignore(); }
here's the file Duck, Donald 45 3.50 60 Mouse, Mickey 35 6.50 55 Brown, Charlie 35 3.00 20 Oyle, Olive 40 4.50 60 Man, He 45 7.50 20 Ra, She 40 3.50 20 Jetson, George 45 3.50 55 Starr, Brenda 35 8.40 60 Woman, Wonder 40 3.50 55 Jets, Green 45 13.50 55 Barr, Jimmy 35 9.00 60 Evans, Robert 40 8.00 55
You are not creating a new Records instance for each employee, so the end result is that you are replacing the values in the one Records instance and then adding it to the vector N times, where N is the number of records in the file. The best way to avoid this is to create a new Record every time, e.g.: vector<Records*> recordList; // ... while (datafile) { Records* currentRecord = new Records; recordlist.push_back(currentRecord); Records actualRecord = *currentRecord; // same code for setting the values as before } Notably, you are now dealing with a *pointer* to a Records object, rather than a Records object directly. For this reason, I went ahead and created a second local variable, actualRecord, that is the already-dereferenced version of currentRecord, and therefore is not a pointer anymore.
(Also, you should really rename your Records class to Record, as one instance of it only represents a single record ;) )
Join our real-time social learning platform and learn together with your friends!