File Writing with std::string: Unbox the Mysteries
When attempting to write a std::string to a file, users may encounter unexpected results of boxes or corrupted characters. This issue arises from writing the binary data of the string, which contains a pointer and the string length, instead of the actual characters.
For text files, the appropriate solution is to employ an ofstream, which operates like std::cout but directs output to a file. Consider the following example:
#include <fstream> #include <string> int main() { std::string input; std::cin >> input; std::ofstream out("output.txt"); out << input; out.close(); return 0; }
However, if binary data is necessary, the actual string characters should be used. This can be achieved using string::c_str():
write.write(studentPassword.c_str(), studentPassword.size());
The above is the detailed content of How Do I Correctly Write a std::string to a File in C ?. For more information, please follow other related articles on the PHP Chinese website!