Reading and Writing a file using getline

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;
}
Writing to a file
Writing to a file
Output to a file
Output to a file

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;
}
Reading from the file
Reading from the file

One Reply to “Reading and Writing a file using getline”

Leave a Reply

Your email address will not be published. Required fields are marked *