give a c++ example using ofstream
Here is an example that uses ofstream to write data to a file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outputFile("output.txt"); // create an output stream to write to output.txt
if (outputFile.is_open()) { // check if the file was successfully opened
outputFile << "Hello, world!" << endl; // write data to the file
outputFile << "This is a test." << endl;
outputFile.close(); // close the file
cout << "Data written to output.txt." << endl;
} else {
cout << "Error opening output.txt." << endl;
}
return 0;
}
This program creates an output stream to write data to a file called "output.txt". It then checks if the file was successfully opened, and if so, writes two lines of text to the file. Finally, it closes the file and prints a message indicating whether the data was successfully written.
原文地址: https://www.cveoy.top/t/topic/btaN 著作权归作者所有。请勿转载和采集!