When attempting to write a std::string to a file, you may encounter a situation where characters appear as boxes rather than the intended text. This is because the write() method stores binary data in the string object, including a pointer and the data length.
However, writing to a text file requires a different approach. The recommended method is to utilize an ofstream (out-file-stream), which behaves similarly to std::cout but directs output to a file.
To write to a text file using std::string, you can follow these steps:
An example code snippet:
#include <fstream> #include <string> int main() { std::string input; std::cin >> input; std::ofstream out("output.txt"); out << input; out.close(); return 0; }<p><strong>Note:</strong> The out.close() call is not strictly necessary, as the ofstream destructor will automatically handle this when out goes out of scope.</p> <p>If you need to write to a file in binary form, use the c_str() method of the std::string to obtain the actual data:</p> <pre class="brush:php;toolbar:false">write.write(studentPassword.c_str(), studentPassword.size());
The above is the detailed content of How to Properly Write a std::string to a Text File in C ?. For more information, please follow other related articles on the PHP Chinese website!