How to write text file code snippet

Summary

Source code of C++ program, demonstrating how to write to text file.

Source code

C++: write_to_text_file.cpp

#include <fstream>

#include <iostream>

#include <string>

 

using namespace std;

 

int main() {

      // sample text

      string sampleText[] = { "Sample text",

            "Line 1",

            "Line 2",

            "Line 3",

            "The last line."

      };

      // try to open a file for writing

      ofstream ofs("sample_file.txt", ofstream::out);     

      if (ofs.good())   { // if opening is successful

            // iterate through lines of sample text

            for (int i = 0; i < 5; i++)

                  // and print every line to the file

                  ofs << sampleText[i] << endl;

            // close the file

            ofs.close();

      } else

            // otherwise print a message

            cout << "ERROR: can't open file for writing." << endl;

 

      return 0;

}

 

Sample run (contents of sample_file.txt)

C/C++

Sample text
Line 1
Line 2
Line 3
The last line.