Home >Backend Development >C++ >Why Does Writing a std::string to a File Produce Boxes Instead of Text?

Why Does Writing a std::string to a File Produce Boxes Instead of Text?

Linda Hamilton
Linda HamiltonOriginal
2024-11-26 21:00:171026browse

Why Does Writing a std::string to a File Produce Boxes Instead of Text?

How to Write a std::string to File Without Seeing Boxes

Question:

When writing a std::string variable to a file using the write() method, the resulting file displays boxes instead of the expected string. Is std::string suitable for this scenario, or should an alternative approach be considered?

Answer:

std::string is indeed suitable for writing to files, but the write() method is intended for binary data. To write a string in text format, consider using an ofstream object. Here's an example:

#include <fstream>
#include <string>
#include <iostream>

int main() {
    std::string name;
    std::cout << "Enter your name: ";
    std::cin >> name;
    std::ofstream out("name.txt");
    out << name;  // Writes the string to the file in text format
    out.close();
    return 0;
}

For binary writing, use the c_str() method to obtain the underlying character data and write it to the file:

#include <fstream>
#include <string>
#include <iostream>

int main() {
    std::string password;
    std::cout << "Enter your password: ";
    std::cin >> password;
    std::ofstream out("password.bin", std::ios::binary);
    out.write(password.c_str(), password.size());  // Writes the password in binary format
    out.close();
    return 0;
}

The above is the detailed content of Why Does Writing a std::string to a File Produce Boxes Instead of Text?. 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