File Streams
ofstream writes and ifstream reads files. Check that the file opened, and the stream closes itself when it goes out of scope.
Example
#include <fstream>
#include <sstream>
{
ofstream out("demo_cpp.txt");
out << "alpha\nbeta\ngamma\n";
}
ifstream in("demo_cpp.txt");
string line; int n = 0;
while (getline(in, line)) cout << ++n << ":" << line << " ";
cout << "\n";
in.close();
remove("demo_cpp.txt");Result
1:alpha 2:beta 3:gamma
Exercise
Read a file.
std:: in("a.txt");
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.