I can foresee problems with the format of the data in the file.
It's already apparent from the sample presented earlier:
john
grace
20
johnman@hotmail.com
20
stcatherines
lu31ul
|
There are two related problems. One, individual pieces of data may contain spaces. UK postcodes are normally shown with a space, such as "LU3 1UL" and a street name may consist of several individual words, for example "St. Catherines Avenue".
Secondly, a piece of data may be missing. For example you may have a street address but no email, or vice versa.
A solution to both of these problems is to place all of the data for an individual on a single line in the file. Each item is separated by a delimiter, such as a comma or a tab.
Then, this function will change from this:
1 2 3 4 5 6 7 8 9 10 11 12
|
// define operator >> for a Details object
istream& operator>>( istream& is, Details& detail )
{
is >> detail.FirstName;
is >> detail.LastName;
is >> detail.Age ;
is >> detail.Email;
is >> detail.DoorNumber;
is >> detail.RoadName;
is >> detail.PostCode;
return is;
}
|
to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
// define operator >> for a Details object
istream& operator>>( istream& is, Details& detail )
{
string line;
string word;
char delim = '\t';
getline(is, line);
istringstream iss(line);
getline(iss, word, delim);
detail.FirstName = word;
getline(iss, word, delim);
detail.LastName = word;
getline(iss, word, delim);
detail.Age = atoi(word.c_str()); // convert string to integer
getline(iss, word, delim);
detail.Email = word;
getline(iss, word, delim);
detail.DoorNumber = atoi(word.c_str()); // convert string to integer
getline(iss, word, delim);
detail.RoadName = word;
getline(iss, word, delim);
detail.PostCode = word;
return is;
}
|
That will handle data which looks like this, where '\t' is the tab character:
john\tgrace\t20\tjohnman@hotmail.com\t20\tSt Catherines Ave\tLU3 1UL\n
|
Of course this change will need to be mirrored in the code which outputs the data to the file. That change is relatively straightforward, simply outputting the tab delimiter between the items, and a single newline at the end of each record.
Note, the code I posted here could be shortened a bit. I left it like that to show what is going on.