In this program, we will use getline function to read and write the data from/into a file. While loop is used to verify the end of the file.
Program to write to a file.
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream out;
string line;
out.open("test.txt",ios::trunc|ios::binary);
while(out){
getline(cin,line);
if(line=="-1") break;
out<<line<<endl;
}
out.close();
return 0;
}


Program to read from a file
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ifstream ifile;
string line;
ifile.open("test.txt");
if(!ifile.is_open()){
cout<<"No file found"<<endl;
return -1;
}
while(ifile){
getline(ifile,line);
cout<<line<<endl;
}
return 0;
}
