C++ how to save data about a object code example
Example: C++ how to save data about a object
#include <fstream>
#include <iostream>
class Something
{
public:
int weight;
int size;
friend std::ostream& operator<<(std::ostream& os, const Something& s)
{
os << s.weight << '\n';
os << s.size;
return os;
}
friend std::istream& operator>>(std::istream& is, Something& s)
{
is >> s.weight >> s.size;
return is;
}
};
int main()
{
Something s1;
Something s2;
s1.weight = 4;
s1.size = 9;
std::ofstream ofs("saved.txt");
ofs << s1;
ofs.close();
std::ifstream ifs("saved.txt");
if(ifs >> s2)
{
std::cout << s2 << '\n';
}
return 0;
}