Open In App

How to Read Input Until EOF in C++?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to use getline() to read input until EOF is
// reached.
  
#include <fstream>
#include <iostream>
#include <string>
  
using namespace std;
  
int main()
{
    // Specify filename to read (replace with your actual
    // file)
    string filename = "input.txt";
  
    // Open file for reading
    ifstream inputFile(filename);
  
    // Check file open success
    if (!inputFile.is_open()) {
        cerr << "Error opening file: " << filename << endl;
        return 1;
    }
  
    // String to store each line
    string line;
  
    // Read each line until EOF
    cout << "The file contents are: \n";
    while (getline(inputFile, line)) {
        // Process each line (replace with your logic)
        cout << line << endl;
    }
  
    // Close file when done
    inputFile.close();
  
    return 0;
}


Output

The file contents are: 
This file contains some
random text that
can be scanned by
a C++ program.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads