Loading custom data from file


I've been trying to get my head around file management lately, and I've almost got it, I think. I've written a test program in which the user creates an object with some data, and can save that to file and load it again. The class from which the object is created has a string and an int. When loaded, each the string and int from the object is displayed. However, only the int seems to work. The it shows up nicely, but the string doesn't show up at all. Here's my code, sorry if its a bit crude at the moment:

http://pastebin.org/315101

Does anyone know what I'm doing wrong?

Fafner
Please? =P
You can't just dump objects directly to a file like that. Objects often contain pointers that expect to be pointing at valid memory. In order to be pointing at valid memory, the memory needs to have been allocated by the runtime system, rather than by reading the address from a file.

A std::string contains a pointer to its actual representation. So the string object needs to manage the setting of its internal pointers, they are runtime sensitive and can not survive being written to and later read from a file.

One way to store your object in a file is to write input and output operators for your class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <fstream>
#include <string>

class A
{
	// give output operator access
	friend std::ostream& operator<<(std::ostream&, const A&);

	// give iutput operator access
	friend std::istream& operator>>(std::istream&, A&);

public:
	int i;
	std::string s;
};

/**
 * This function is called to output your object to a stream such as a file
 */
std::ostream& operator<<(std::ostream& os, const A& a)
{
	os << a.i << ' ' << a.s << '\n';
	return os;
}

/**
 * This function is called to input your object from a stream such as a file
 */
std::istream& operator>>(std::istream& is, A& a)
{
	is >> a.i >> a.s;
	return is;
}

int main()
{
	A a;
	a.i = 4;
	a.s = "whoopdidoo";

	std::cout << "a.i = " << a.i << '\n';
	std::cout << "a.s = " << a.s << '\n';
	std::cout << std::endl;

	std::ofstream ofs("test.txt");
	ofs << a; // this calls the output operator for your class
	ofs.close();

	a.i = 0;
	a.s = "";

	std::cout << "a.i = " << a.i << '\n';
	std::cout << "a.s = " << a.s << '\n';
	std::cout << std::endl;

	std::ifstream ifs("test.txt");
	ifs >> a; // this calls the input operator for your class
	ifs.close();

	std::cout << "a.i = " << a.i << '\n';
	std::cout << "a.s = " << a.s << '\n';
	std::cout << std::endl;

	return 0;
}
a.i = 4
a.s = whoopdidoo

a.i = 0
a.s = 

a.i = 4
a.s = whoopdidoo


Last edited on
Great, thanks! Sorry for double post btw
Topic archived. No new replies allowed.