Class Ouput with I/O buffer

Hi Guys,

Using and older C++ book, about 12 years old if that may have some significance. I am sure I wrote the example down verbatim, but when I enter a name and age, the output to the file is nothing more than what looks like Chinese characters. Does anyone know where my mistake is?

Thanks,

Mike

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
class Person{

public:
	void get_person(){
		cout<<"Enter name: ";
		cin>>name;
		cout<<"Enter age: ";
		cin>>age;
	}
	void show_data(){
		cout<<"Name: "<<name<<endl;
		cout<<"Age:"<<age<<endl;
	
	}
private:
	char name[50];
	int age;
};

int main()	
{
	Person person;
	person.get_person();
	
	ofstream output_file("C:/Users/Mike/Desktop/fdata.txt", ios::binary);
	
	output_file.write(reinterpret_cast<char*>(&person),sizeof(person));

	person.show_data();

	_getch();   
	return 0;
}
I guess you opened the file using notepad. When you open a binary file using notepad, this usually happens. This is because the data of the 'age' variable isn't usual text. Try

1
2
3
4
ifstream input_file("C:/Users/Mike/Desktop/fdata.txt",ios::binary);
Person person;
input_file.read(reinterpret_cast<char*>(&person),sizeof(person));
person.show_data();


If the data shown is wrong, then there is a problem.
I am a little confused, although what you say about the notepad is correct. It's the person.show_data() which is displaying the object, the line

input_file.read(reinterpret_cast<char*>(&person),sizeof(person));

is not doing anything as far as I can tell. Is there some subteltie I am missing?

This is what I have now, without your redecleration of Person:

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
class Person{

public:
	void get_person(){
		cout<<"Enter name: ";
		cin>>name;
		cout<<"Enter age: ";
		cin>>age;
	}
	void show_data(){
		cout<<"Name: "<<name<<endl;
		cout<<"Age:"<<age<<endl;
	
	}
private:
	char name[50];
	int age;
};

int main()	
{
	Person person;
	person.get_person();
	
	ofstream output_file("C:/Users/Mike/Desktop/fdata.txt", ios::binary);
	
	output_file.write(reinterpret_cast<char*>(&person),sizeof(person));


	ifstream input_file("C:/Users/Mike/Desktop/fdata.txt",ios::binary);
	
	input_file.read(reinterpret_cast<char*>(&person),sizeof(person));
	person.show_data();


	_getch();   
	return 0;
}

The ios::binary is defiantly the issue here... I suggest using ios::out for writing, then ios:: in for reading.

- Kyle
I did change it to ios:: out and ios::in but to no avail. I might have to do a little digging online tomorrow, as it's getting late.

Thanks for all your help guys!

Topic archived. No new replies allowed.