How to write text file

Submitted by:Pitter Alderson

Date added:04 May, 2013

Category:C++

C++ code example shown here how to write to text file.

Tags: write text file

Code Snippet:

#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;
}
 
 

Comments