The read method returns the last object twice. I tried using tellg before read line and it seems as if the last object itself is written twice in file.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Abc
{
string uname, pword;
public:
void getdetails()
{
cout << "enter a password";
getline(cin, pword);
cout << "enter username";
getline(cin, uname);
}
void printdetails()
{
cout << uname << " " << pword;
}
};
int main()
{
fstream f;
int i, j;
f.open("gamma.txt", ios::out | ios::binary | ios::app);
Abc a;
for (i = 0; i < 2; i++)
{
a.getdetails();
f.write((char*) &a, sizeof(a));
}
f.close();
f.open("gamma.txt", ios::in | ios::binary);
for (i = 0; i < 2; i++)
{
f.read((char*) &a, sizeof(a));
a.printdetails();
}
f.close();
}
This is the output. Instead of getting both the objects I'm getting the second one twice.
enter a password
123
enter username
ralph
enter a password
321
enter username
john
john 321john 321