How to Read Input Until EOF in C++?
Last Updated :
31 Jan, 2024
In C++, EOF stands for End Of File, and reading till EOF (end of file) means reading input until it reaches the end i.e. end of file. In this article, we will discuss how to read the input till the EOF in C++.
Read File Till EOF in C++
The getline() function can be used to read a line in C++. We can use this function to read the entire file until EOF by using it with a while loop. This method reads the file line by line till the EOF is reached.
C++ Program to Read Input Until EOF
C++
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string filename = "input.txt" ;
ifstream inputFile(filename);
if (!inputFile.is_open()) {
cerr << "Error opening file: " << filename << endl;
return 1;
}
string line;
cout << "The file contents are: \n" ;
while (getline(inputFile, line)) {
cout << line << endl;
}
inputFile.close();
return 0;
}
|
Output
The file contents are:
This file contains some
random text that
can be scanned by
a C++ program.
Share your thoughts in the comments
Please Login to comment...