write and read string to binary file C++

后端 未结 7 800
暖寄归人
暖寄归人 2020-12-09 12:46

Im having problems writing string into a binary file. This is my code:

ofstream outfile(\"myfile.txt\", ofstream::binary);
std::string text = \"Text\";
outfi         


        
7条回答
  •  旧时难觅i
    2020-12-09 13:27

    the line

    outfile.write((char*) &text, sizeof (string));
    

    is not correct

    sizeof(string) doesn't return the length of the string, it returns the sizeof the string type in bytes.

    also do not cast text to char* using a C cast, you can get hold of the char* by using the appropriate member function text.c_str()

    you can simply write

    outfile << text;
    

    instead.

提交回复
热议问题