Write/Reade array of struct to file

I'm stuck on writing array of struct to file and then read from it.
Here is my test code. Can anybody point me where i'm wrong?
I need use array not vectors and i am willing to write using c++ not c.

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

fstream file;
struct test
{
char a[10];
int b;
}x[2];
int main()
{
	int tp, length;
	for (int i=0; i<2; i++)
	{
		cin>>x[i].a;
		cin>>x[i].b;
		cout<<endl;
	
	}
	file.open ("test.txt", ios::out);
	if(file)
	{
		file.write((char*)x,sizeof(test));
	}
	else
	cout <<"Error opening the file!\n";
	file.close();

	file.open("test.txt", ios::in);
	length=file.tellp();
	file.seekg(0,ios::beg);
	tp = length/sizeof(test);
	test *temp= new test[tp];
	if(file)
	{
	file.read((char*)temp,tp*sizeof(test));
	}
	else{cout<<"error reading from file\n";}
	cout<<tp;
	for(int i = 0; i<tp; i++)
	{
		cout<<temp[i].a;
		cout<<temp[i].b;
	}
	file.close();
 
	system("pause");
	return 0;
}
What is the problem?
What format do you want the text written into your text file?

word <space> number
word <space> number

-or-

word
number
word
number

-or-

????
Topic archived. No new replies allowed.