c 2b 2b how to save data about a object

Solutions on MaxInterview for c 2b 2b how to save data about a object by the best coders in the world

showing results for - "c 2b 2b how to save data about a object"
Riccardo
15 Jul 2016
1#include <fstream>
2#include <iostream>
3
4class Something
5{
6public:
7	int weight;
8	int size;
9
10	// Insertion operator
11	friend std::ostream& operator<<(std::ostream& os, const Something& s)
12	{
13		// write out individual members of s with an end of line between each one
14		os << s.weight << '\n';
15		os << s.size;
16		return os;
17	}
18
19	// Extraction operator
20	friend std::istream& operator>>(std::istream& is, Something& s)
21	{
22		// read in individual members of s
23		is >> s.weight >> s.size;
24		return is;
25	}
26};
27
28int main()
29{
30	Something s1;
31	Something s2;
32
33	s1.weight = 4;
34	s1.size = 9;
35
36	std::ofstream ofs("saved.txt");
37
38	ofs << s1; // store the object to file
39	ofs.close();
40
41	std::ifstream ifs("saved.txt");
42
43	// read the object back in
44	if(ifs >> s2)
45	{
46		// read was successful therefore s2 is valid
47		std::cout << s2 << '\n'; // print s2 to console
48	}
49
50	return 0;
51}
similar questions
queries leading to this page
c 2b 2b how to save data about a object