Home >Backend Development >C++ >How Do I Correctly Write a std::string to a File in C ?

How Do I Correctly Write a std::string to a File in C ?

DDD
DDDOriginal
2024-11-25 22:49:13879browse

How Do I Correctly Write a std::string to a File in C  ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn