So today I made almost no progress programming because I very slowly realized that C++ is a very type-cased sensitive language in the respect that I cannot append a structure to
std::string is a class that stores pointers to another memory location where the actual string is stored. If you write std::string to file, only the bytes representing the pointers is written, not the string itself.
Do NOT use reinterpret_cast
for serialization/deserialization or stringification. reinterpret_cast
is a very dangerous tool that should be used only in very particular situations. The correct way of dealing with your issue is to provide an operator<<
and an operator>>
for your Info
class. Example:
std::ostream& operator<<(std::ostream& os, const Info& p)
{
os << name;
os << weight;
os << grade;
return os;
}
reinterpret_cast<T>
literally asks the compiler to look at a memory location and act as if it were a T
. Classes like std::string
are complicated: they own resources and store pointers to other memory locations inside them. If you attempt to write the bytes of an std::string
out, you'll get garbage, as your characters are likely not stored with the std::string
instance itself...