I am trying to read a file use the data line by line to create into an object.
The current file I have is like this and the code reading the file will be found below.
1223 Fake1 Name1 60 70 80 24 89 add1 Male
1224 Fake2 Name2 61 70 81 80 24 add2 Male
1225 Fake3 Name3 63 70 82 80 89 add3 Male
1226 Fake4 Name4 63 70 83 80 88 add4 Male
The problem I am having is that I need to put delimiters in the file so that a person can have more than one name and also the address can now hold multiple strings until the delimiter.
I would like to change my file to this;
1223 : Fake1 Name1 : 60 : 70 : 80 : 24 :89 : This will be address1 : Male
1224 : Fake2 Name2 : 61 : 70 : 81 : 80 :24 : This will be address2 : Male
1225 : Fake3 Name3 : 63 : 70 : 82 : 80 :89 : This will be address3 : Male
1226 : Fake4 Name4 : 63 : 70 : 83 : 80 :88 : This will be address4 : Male
How can I update the code below so that it can use the delimiters to create an object?
Thank you for the response. I have tried implementing similar code but the problem is that it takes the whole file and stores it string by string. Its from there where I am actually struggling to only the values for the first line and storing that into an object before proceeding to the next lines.
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
int main() {
std::ifstream infile("people2.txt");
if (!infile) {
std::cerr << "Could not open file." << std::endl;
return 1;
}
std::string line;
while (std::getline(infile, line)) { // Read file line by line.
std::string field;
std::vector<std::string> separated_fields;
std::istringstream iss_line(line);
while (std::getline(iss_line, field, ':')) { // Split line on the ':' character
separated_fields.push_back(field); // Vector containing each field, i.e. name, address...
}
// Do something with the results
separated_fields[0]; // ID
separated_fields[1]; // Names
separated_fields[2]; // Number
separated_fields[3]; // Number
separated_fields[4]; // Number
separated_fields[5]; // Number
separated_fields[6]; // Number
separated_fields[7]; // Address
separated_fields[6]; // Sex
}
}