C. Writing to a File
Writing to a file in C++ is similar to printing output to the terminal. To write to a file, one creates an object of type ofstream and specifies the name and extension of the file. Then, use the insertion operator (<<) to add content to the file.
Here’s an example to demonstrate how to write to a file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string str = "Welcome_To_studentproject!";
ofstream out("example.txt");
out << str;
out.close();
return 0;
}
Output:
Welcome_To_studentproject!
D. Reading a file
Reading from a file in C++ is similar to reading input from the terminal. To read from a file, you need to create an object of the type ifstream and specify the name of the file along with its extension. You then use the extraction operator (>>) to extract data from the file fed to the object. An example is provided to demonstrate how to read from a file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string str;
ifstream in("example.txt");
in >> str;
cout << str;
return 0;
}
The file example.txt had “Welcome_To_studentproject!” as its content, hence the output:
Welcome_To_studentproject!