c++ - How to use seekg with string input to get a record from a binary file -


my sample text file this:

name: first email: first@gmail.com  name: second email: second@gmail.com 

currently wrote function read record specified binary file:

staff getarecord (fstream& afile, const char filename [], int k) {     afile.open (filename, ios::in | ios::binary);      staff s;      afile.seekg ((k - 1) * sizeof (staff), ios::beg);     afile.read (reinterpret_cast <char *>(&s), sizeof (s));      afile.close ();     return s; } 

staff structure consist of name , email field. record based on user input:

int k;  cout << "enter email: "; cin >> k;  staff s = getarecord(afile,"staff.dat",k); 

then i've read data if user's input numeric(1 , 2 since have 2 records) sake of seekg function, how can retrieve same result if user input email instead of record number?

as mentioned in comments, there serious concerns way loading data staff structure: lines afile.seekg(...); afile.read(...); weird: seekg should not work expect. file text file, should use text techniques: operator >> or getline method.

if want load staff item directly file, can overload operator>>: (this example, should improved)

struct staff{     string name, email; };  istream& operator>>(istream& is, staff& staff) {     string s;     while(is >> s && s != "name:"); // "name:"      staff.name = "";     while(is >> s && s != "email:"){ // "email:"         staff.name += s + " "; // load name (if multiple words)     }     staff.email = s; // load email      // handle errors     if(/* couldn't load staff */)         is.setstate(std::ios::failbit);      return is; } 

then, if want search, have no choice read file beginning:

staff staff;  // search id for(int i=0 ; i<=k ; i++)     afile >> staff; return staff;  // search email while(afile >> staff){     if(staff.email == email)         return staff; } return /*error*/; 

Comments