Lesson 2
Reading Text Files Line-by-Line in C++
Introduction and Context Setting

Welcome to this lesson, where we'll explore an essential technique in text data manipulation: reading files line-by-line. In many real-world applications, processing data one line at a time is crucial for effective data management, particularly when dealing with large files like logs or data streams. By the end of this lesson, you'll understand how to efficiently read and process file data line-by-line using C++ and the <fstream> library.

Recall: Opening Files

As a quick reminder from our previous lesson, let's revisit how opening files in C++ works. File handling is done using the <fstream> library, specifically with std::ifstream for reading files. You specify the file path and create an ifstream object to open and handle the file:

C++
1#include <fstream> 2#include <string> 3 4int main() { 5 std::string file_path = "input.txt"; 6 std::ifstream file(file_path); 7 8 // File processing goes here 9 10 return 0; 11}

In this example, file_path is a string that indicates the location of your file, and file is an ifstream object handling the file.

Understanding `std::getline()`

The std::getline() function reads a line from an input stream into a string. This function is a part of the library. Its syntax is:

C++
1std::getline(input_stream, string_variable);
  • input_stream: The source, like an ifstream.
  • string_variable: The string where the line is stored.

std::getline() reads until a newline is found or the end of the file is reached, extracting but not storing the newline. This makes it ideal for line-based data.

Using std::getline() as a condition in a while loop is straightforward:

C++
1while (std::getline(file, line)) { 2 // Process the line 3}

It returns true if a line is successfully read, allowing the loop to continue, and false at the end of the file, exiting the loop.

Reading Files Line-by-Line

To read a file line-by-line in C++, use the std::getline() function. Let's see this in action:

C++
1#include <fstream> 2#include <iostream> 3#include <string> 4 5int main() { 6 std::string file_path = "input.txt"; 7 std::ifstream file(file_path); 8 std::string line; 9 10 std::cout << "Reading file line-by-line:\n"; 11 while (std::getline(file, line)) { 12 std::cout << line << std::endl; 13 } 14 15 return 0; 16}

Here, getline reads lines from input.txt one-by-one. Each line is stored in the line variable and then printed to the console.

Reading Integers from a File and Finding Their Sum

Let's put our reading skills to use by reading integers from a file and calculating their sum. The task is to open a file containing numbers, read each integer, and find their cumulative total. For reading numbers, we can simply use the stream extraction operator (>>) with ifstream since it naturally reads and converts data to the appropriate type:

Assume numbers.txt contains:

Plain text
110 220 330 440

The following code reads integers from this file and calculates their sum:

C++
1#include <fstream> 2#include <iostream> 3#include <string> 4 5int main() { 6 std::string file_path = "numbers.txt"; 7 std::ifstream file(file_path); 8 int number, total_sum = 0; 9 10 while (file >> number) { 11 total_sum += number; // Add the integer to total_sum 12 } 13 14 std::cout << "The sum of the numbers is: " << total_sum << std::endl; 15 16 return 0; 17}
  • Reading Numbers: Each number is read directly into an integer variable.
  • Calculating Sum: The integers are added together in the total_sum variable.

After executing this code, the output displays the total sum of the numbers:

Plain text
1The sum of the numbers is: 100
Summary and Practice Preparation

In this lesson, you gained the skills to read a text file line-by-line using C++ — a fundamental technique for processing large datasets efficiently. You've learned to manage file I/O operations using ifstream, explored how to utilize std::getline(), and handled string processing in C++.

Now, you're ready to dive into practice exercises where you can apply these concepts and strengthen your understanding. Continue to build on these skills as we explore further parsing techniques in future lessons. Keep up the great work!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.