wrong output

hi guys I am writing a struct to a binary file and copying the data to a new struct anyway I am getting weird out put for some reason it prints 65adam instead of adam,

anybody know why cout << sample.a produces 65adam?

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



#pragma pack(push,1))
struct sample{

	char a[60];
	int b;
	char c;
};
#pragma pack(pop)
// https://stackoverflow.com/questions/3318410/pragma-pack-effect


int main() {


	sample samp = {"Adam",185,'a'};
	ofstream out;
	string fileName = "IO7.bin";

	out.open(fileName,ios::binary);
	cout << sizeof(sample);

	out.write((char *)(&samp),sizeof(sample));

	out.close();

	sample samp2 = {};
	ifstream input;

	input.open(fileName,ios::binary);

	input.read((char *)&samp2,sizeof(sample));

	cout << samp2.a << samp2.b << samp2.c;

	input.close();

}
Hello adam2016,

Change line 26 to cout << sizeof(sample) << std::endl; and see what you get.

Hope that helps,

Andy
nice spot andy,don't know how I didn't catch that
Hello adam2016,

It is always the simple things that get you.

Glad it makes sense now.

Andy
Topic archived. No new replies allowed.