Reading from a file using ifstream

ifstream class is a file stream class, used to read a file. In this article, we will write a program to read the data from a file.

The code calls myfile.txt we created here. And then we read the data from the files using two different methods.

#include<iostream>
#include<fstream>
using namespace std;
int main(){
	ifstream in;
	in.open("myfile.txt");
	if(!in.is_open()){
		cout<<"Can't open file"<<endl;
		return 1;
	}
	char a[20];
	int b;
	in>>a>>b;
	cout<<a<<" "<<b<<endl;
	in>>a>>b;
	cout<<a<<" "<<b<<endl;
	in>>a>>b;
	cout<<a<<" "<<b<<endl;
	return 0;
}
output of the above program. ifstream
output of the above program. ifstream

We can write the program in the other way as shown below.

#include<iostream>
#include<fstream>
using namespace std;
int main(){
	ifstream in;
	string line;
	in.open("myfile.txt");
	if(!in.is_open()){
		cout<<"Can't open file";
		return -1;
	}
	cout<<"File opened."<<endl;
	while(getline(in,line)){
		cout<<line<<endl;
	}
	in.close();
	return 0;
}
output of the above program. ifstream
output of the above program. ifstream

Leave a Reply