debug read/write string to binary file

前端 未结 3 1732
醉梦人生
醉梦人生 2020-12-19 17:12

I am trying to write to a binary file , here is my snippet of code

#include 
#include 
#include 

using namespac         


        
3条回答
  •  一生所求
    2020-12-19 17:40

    You are storing the raw data of a struct that, in fact, contains only pointers. That’s the way std::string uses for storing data in order to make the string resizeable. The only reason your program does print any data is that in the moment of reading, the object person still exists. If you put the reading part of your program into a separate program, you won’t be able to read any data.

    To actually store your data using fstream, you can store one string per line, for example:

    afile << person.ID << endl;
    afile << person.password << endl;
    

    The file user.dat:

    001
    abc
    002
    def
    

    And you can read it this way:

    afile >> person.ID >> person.password;
    while (afile.good())
    {
      cout<> person.ID >> person.password;    
    }
    

    You should also check Serializing a class which contains a std::string.

提交回复
热议问题