I'm trying to read a .bin file that I have made that include two integers and one string inside a struct. The int shows fine, but somehow the string output shows weird symbols.
This is the write script:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct student{
int no;
string name;
int score;
};
int main(){
fstream myFile;
myFile.open("data.bin", ios::trunc | ios::out | ios::in | ios::binary);
student jay, brad;
jay.no = 100;
jay.name = "Jay";
jay.score = 95;
brad.no = 200;
brad.name = "Brad";
brad.score = 83;
myFile.write(reinterpret_cast<char*>(&jay),sizeof(student));
myFile.write(reinterpret_cast<char*>(&brad),sizeof(student));
myFile.close();
cin.get();
return 0;
}
and this is the read script:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct student{
int no;
string name;
int score;
};
int main(){
fstream myFile;
myFile.open("data.bin", ios::in | ios::binary);
student readFile;
myFile.seekp(1*sizeOf(student)); //I use this because I want only specific position
//to be shown, for example I put 1 to show only Brad
myFile.read(reinterpret_cast<char*>(&readFile),sizeof(student));
cout << "No : " << readFile.no << endl;
cout << "Name : " << readFile.name << endl;
cout << "Score: " << readFile.score << endl;
myFile.close();
cin.get();
return 0;
}
The result would be like this:
No : 200
Name : ñ∩K
Score: 83
The string showed "ñ∩K" instead of "Brad".
I tried not to use seekp
, and using read twice:
myFile.read(reinterpret_cast<char*>(&readFile),sizeof(student));
cout << "No : " << readFile.no << endl;
cout << "Name : " << readFile.name << endl;
cout << "Score: " << readFile.score << endl;
myFile.read(reinterpret_cast<char*>(&readFile),sizeof(student));
cout << "No : " << readFile.no << endl;
cout << "Name : " << readFile.name << endl;
cout << "Score: " << readFile.score << endl;
The result would be:
No : 100
Name : Jay
Score: 95
No : 200
Name : ε@
Score: 83
As you can see, the first position shows "Jay" fine but the next one is not. Any idea what went wrong? I'm new to C++.