c++ create text file and write to it code example
Example 1: create new file c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream MyFile("filename.txt");
MyFile << "Files can be tricky, but it is fun enough!";
MyFile.close();
Example 2: How to read a file in in C++
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
int sum = 0;
int x;
ifstream inFile;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1);
}
while (inFile >> x) {
sum = sum + x;
}
inFile.close();
cout << "Sum = " << sum << endl;
return 0;
}
Example 3: write to file in C++
ofstream myfile;
myfile.open("file.txt");
myfile << "write this to file"