0

Here is my struct:

struct SV {
string masv;
string ho, ten, gioitinh;
string malop;
float ds_diem[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};

As you can see it have a few string and an array of float. I've tried to write and load it using these code:

Write:

fout.write((char *)&dssv[i],sizeof(SV));

Read:

fin.read((char *)&sv,sizeof(SV));

They didn't work obviously. And i think it have to do something with char and string. I do try to search for solution, but the codes that posted by the asker are to complex for my to understand a single line, let alone the answer. So a simple and genuine answer would be very appreciated.

PS: Forgot to mention I saved it as a .dat file.

  • 2
    When writing or reading raw structures, they need to be [POD types](https://en.cppreference.com/w/cpp/named_req/PODType) or [trivial types](https://en.cppreference.com/w/cpp/named_req/TrivialType). `std::string` is neither and that makes your structure also non-POD and non-trivial. You might want to do research about [*serialization*](https://en.wikipedia.org/wiki/Serialization) if you want to save in raw binary form, or use a text-format instead. – Some programmer dude Dec 10 '18 at 08:24
  • so how do i save it in a text-format ? – Thạch Hải Đăng Dec 10 '18 at 08:30
  • `fout << dssv[i].masv << '\n';` etc.? – Some programmer dude Dec 10 '18 at 08:35
  • do I need to change the ios::binary when create the ofstream to something else ? An also how to read it ? – Thạch Hải Đăng Dec 10 '18 at 08:39
  • You should not use `ios::binary` for text files. And [`std::getline`](https://en.cppreference.com/w/cpp/string/basic_string/getline). And perhaps [get a couple of good beginners books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282)? – Some programmer dude Dec 10 '18 at 08:42
  • 1
    At least read some FAQ about C++, at least the questions about serialization. https://isocpp.org/wiki/faq/serialization It is not trivial topic. – Öö Tiib Dec 10 '18 at 09:24

0 Answers0