Writing to a file
Lesson 12 of 23 in Coddy's C++ File Handling course.
Now, for writing to a file to be performed we first need to open the file in outputting mode, which means we need to open the file using an object from the ofstream instead of the ifstream class.
Writing to a file, compared to reading from one is quite easier. Almost every time we will use the << operator. Other options do exist, for example:
.put(char)- It appends the character specified to the file.write(string, length n)- it appends n characters from the string specified to the file
But, for general needs, the << operator does the job as we can write anything we want.
ofstream myfile;
myfile.open("example.txt");
if (myfile.is_open()) {
myfile << "Line 1" << endl;
myfile << "Line 2" << endl;
myfile << "Line 3" << endl;
}
myfile.close()Content of "example.txt":
Line 1
Line 2
Line 3Challenge
EasyOn standard input you'll be given a
- name (string)
- age (int)
Open the file output.txt and write the message My name is {name} and I am {age} years old
*Do not change the default code*
Try it yourself
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Enter your code here
// DO NOT CHANGE THE CODE BELOW!
ifstream file("output.txt");
string line;
while(!file.eof()){
getline(file, line);
cout << line;
}
file.close();
}