How to Read a File Line by Line in C++?
Last Updated :
05 Feb, 2024
In C++, we can read the data of the file for different purposes such as processing text-based data, configuration files, or log files. In this article, we’ll learn how to read a file line by line in C++.
Read a File Line by Line in C++
We can use the std::getline() function to read the input line by line from a particular stream. We can redirect the getline() to the file stream to read the file line by line.
C++ Program to Read File Line by Line
C++
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream file( "GFG.txt" );
string line;
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
else {
cerr << "Unable to open file!" << endl;
}
return 0;
}
|
Input File: GFG.txt
GFG.txt
Output
Share your thoughts in the comments
Please Login to comment...