As Jochen Arndt said, you are not saving the string correctly, and, as a result, it isn't read correctly either. More importantly, at the end of the program, the destructor of that
string
is called, assuming a correctly initialized
string
- and at that point it crashes.
Your problem starts with
reinterpret_cast
: my advice on that is:
1.
as a general rule, never cast anything to a different type. If types don't match, then the most likely reason is that (a) your variable(s) weren't defined with the correct type to start with, or (b) the variable or function that you try to use with your variable wasn't defined with the right type. Try to fix that, if possible.
2. If you must cast, use
const_cast
,
dynamic_cast
, or
static_cast
- whichever is appropriate.
3. If neither of the above works, rewrite your program to avoid the cast altogether, or at worst can get away with case 2. above.
Using
reinterpret_cast
is a surrender: you give up on static typing and all the advantages that come with it, replacing it with managing bytestreams. This can work, but only if you fully understand the format of the actual data, and have full control of it's management. In this case, you have neither.
Based on this, my suggestion is to solve that problem according to case 3. above: rewrite your program, i. e. the parts that deal with writing and reading the data. There are other functions that are fully capable of writing and reading
std::string
objects, so do use those, not binary output functions:
void write_sal(fstream& f, const sal& s) {
f << s.name << endl << s.y <<endl;
}
sal read_sal(fstream& f) {
sal s;
f >> s.name >> s.y;
return s;
}
There. No casting required. I haven't tested it: the additional
endl
that I added to the output may not be needed, you might need to test that.
P.S.:
The streaming operator
operator>>(std::basic_string&)
will only read up to the first whitespace. So, if your input might contain whitespace characters, use the function
std::basic_istream::getline()
instead:
sal read_sal(fstream& f) {
sal s;
std::getline(f, s.name);
f >> s.y;
return s;
}
Now, if your sal object is
{ "What do you get if you multiply six by nine?" , 42 }
, then the first version will only read
{ "What", 0 }
, whereas the above modifiation will correctly read the full text and number.
P.P.S.:
I should mention that mixing different methods to read or write from/to streams can cause problems, because they may use different methods of synchronization. Therefore, to be safe, it would be better to change that last read function like this:
sal read_sal(fstream& f) {
sal s;
std::getline(f, s.name);
std::string sy;
std::getline(f, sy);
s.y = std::stoi(sy);
return s;
}
See
std::getline - cppreference.com[
^]