Home > Backend Development > C++ > body text

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

DDD
Release: 2024-11-25 22:49:13
Original
782 people have browsed it

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;
}
Copy after login

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());
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template