read write binary/text file

Hi,

I have written a program to read from a text file which contain ID and name in this format :

1234567 John Woo
1113456 Kenny Alexis Paton

and write it to a binary file with additional double value at the back like this:

1234567 John Woo 0.0 0.0 0.0 0.0 0.0
1113456 Kenny Alexis Paton 0.0 0.0 0.0 0.0 0.0

The program have no problem doing this until i choose the option to read from the created binary file and write it to a text file. There was no error but my text file contain garbage character.


This is part of my coding:
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

 // open text file with ID and Name and write it to binary file
 

struct markSheet

{

	int id;
	string name;
	double final;
	double a1;
	double a2;
	double a3;
	double exam;
	
};

markSheet r;

	while (!afile.eof())
	{
		
		
		afile >> r.id;
		cout << r.id << endl;
		afile.ignore();
		getline(afile, r.name, '\n');
		cout << r.name << endl;
		r.final = 0.0;
		r.a1 = 0.0;
		r.a2 = 0.0;
		r.a3 = 0.0;
		r.exam = 0.0;
		
	outfile.write (reinterpret_cast <const char *> (&r), sizeof (r));
	}


        //code to read from created binary and write it to a text file

        markSheet r;

        outfile << fixed << showpoint << setprecision(1) ;
	
	while (afile.read (reinterpret_cast <char *> (&r), sizeof (r)))
	{
		outfile 
				<<  r.id << "\t"
				<<  r.name << "\t"
				<<  r.final << "\t"
				<<  r.a1 << "\t"
				<<  r.a2 << "\t"
				<<  r.a3 << "\t"
				<<  r.exam << "\t"
				<<  endl;
	}





I was thinking does saving the r.name as a string got to do with the problem.
Can anyone help identify the problem? Thank you

Topic archived. No new replies allowed.