Menu
Coddy logo textTech

Reading Line by Line

Lesson 8 of 23 in Coddy's C++ File Handling course.

Reading line by line can be performed by opening the file in input mode and then using a string to store each line on its own.

ifstream my_file;
my_file.open("example.txt");

string line;
while(!my_file.eof()) {
	getline(my_file, line);
	cout << line << endl;
}

As you can see, this is how we read line by line, we create an ifstream, then we declare a string called line. We use the while loop to cycle through the file until we reach the end. The .eof() method returns true if we HAVE reached the end of the file, so in this case, we want the loop to keep running as long as we haven't reached it, so that's why we use ! to reverse the value from False to True.

challenge icon

Challenge

Easy

Try to open the file message.txt, then print out the file line by line, but before each line, write the message Next line: and then the next line from the file should be in the next row.

Try it yourself

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    
    // Enter your code here
    
    return 0;
}

All lessons in C++ File Handling