It may be a easy problem...
the method read in stdin or file read in text has been proved be right. Things go wrong in binary read.
Here I have a class named Laptop and a file named laptop.txt, which is written by the code followed. I have reloaded the >>
and <<
using namespace std;
class Laptop
{
private:
string brand;
string cpu;
string ram;
string disk;
int reserve;
public:
Laptop() {}
Laptop(string aBrand, string aCpu, string aRam, string aDisk, int aReserve)
{
this->brand = aBrand;
this->cpu = aCpu;
this->ram = aRam;
this->disk = aDisk;
this->reserve = aReserve;
}
friend ostream &operator<<(ostream &os, const Laptop &laptop)
{
os << laptop.brand << " " << laptop.cpu
<< " " << laptop.ram << " " << laptop.disk << " " << laptop.reserve;
return os;
}
friend istream &operator>>(istream &is, Laptop &laptop)
{
is >> laptop.brand >> laptop.cpu >> laptop.ram >> laptop.disk >> laptop.reserve;
return is;
}
};
int main()
{
fstream file("laptop.txt", ios::out | ios::binary);
vector<Laptop> laptops;
Laptop aLaptop;
for (int i = 0; i < 5; i++)
{
cin >> aLaptop;
laptops.push_back(aLaptop);
}
for (vector<Laptop>::iterator i = laptops.begin(); i != laptops.end(); i++)
{
file.write((char *)(&i), sizeof(*i));
}
return 0;
}
But things doesn't go right in binary read. Here comes to the exception from class Laptop when I try to push aLaptop to the vector. I really don't know why. It's horrible.
int main()
{
fstream file("laptop.txt", ios::in);
vector<Laptop> laptops;
Laptop aLaptop;
while (file.peek() != EOF)
{
file.read((char *)(&aLaptop), sizeof(aLaptop));
laptops.push_back(aLaptop);
}
return 0;
}