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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 14:56:23798browse

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

Writing std::string to a File

When writing a std::string variable to a file, it's important to understand that the write() method writes binary data, which may not be directly readable as text. This can result in boxes appearing in the file when opened.

Suitable Data Structure

For writing single-word strings to a text file, std::string is suitable. Character arrays can also be used, but std::string provides more flexibility and convenience.

Writing to a Text File

The following code demonstrates how to write a std::string to a text file using an ofstream:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  string studentName;
  ofstream write;

  write.open("student.txt", ios::out);
  if (!write.is_open()) {
    cerr << "Error opening file" << endl;
    return 1;
  }

  cout << "Enter student name: ";
  getline(cin, studentName);

  write << studentName << endl;  // Write the string to the file

  write.close();

  return 0;
}

Writing Binary Data

If you need to write the std::string in binary form, use the string::c_str() method to obtain the raw data and then write it to the file:

write.write(studentPassword.c_str(), studentPassword.size());

The above is the detailed content of How Do I Properly 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