Count the Number of Lines in a Text File Using C++

This exercise guides you through the process of writing a C++ program that reads a text file and counts the number of lines it contains. This is a fundamental operation when analyzing or processing files, especially in situations like log parsing, document formatting, or file validation. The program will use the `ifstream` stream and read the file line by line using `getline()`, incrementing a counter with each iteration. By completing this task, you'll become familiar with basic file input operations and how to loop through file content efficiently.

Group

File Management in C++

Objective

1. Create or ensure a text file exists with multiple lines of content.
2. Use `ifstream` to open the file for reading.
3. Read each line using a `while` loop and the `getline()` function.
4. For every line read, increment a counter.
5. Once the end of the file is reached, display the total line count.
6. Properly close the file after reading is complete.

Write a program that calculates the number of lines in a text file.

Example C++ Exercise

 Copy C++ Code
#include <iostream>     // Include for console input and output
#include <fstream>      // Include for file stream operations
#include <string>       // Include for using the string class
using namespace std;

int main() {
    string fileName = "example.txt"; // Name of the file to be read
    ifstream inFile(fileName);       // Open the file for reading
    string line;                     // Variable to hold each line of text
    int lineCount = 0;               // Counter to keep track of the number of lines

    // Check if the file was successfully opened
    if (!inFile) {
        cout << "Error: Could not open the file." << endl;
        return 1; // Exit with an error code
    }

    // Read the file line by line
    while (getline(inFile, line)) {
        lineCount++; // Increment the counter for each line read
    }

    inFile.close(); // Close the file

    // Output the result to the user
    cout << "The file contains " << lineCount << " lines." << endl;

    return 0; // End of program
}

 Output

The file contains 7 lines.

Share this C++ Exercise


More C++ Programming Exercises of File Management in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.

  • Sort the Lines of a Text File Using C++

    This exercise involves creating a C++ program that reads all lines from a text file, sorts them in alphabetical order, and then displays the sorted lines on the screen. Sorting fil...

  • Delete a Specific File Using C++

    In this exercise, you will write a C++ program that deletes a specific file from the system using file handling operations. Managing files programmatically is an essential skill in...

  • ATM Transaction Logger in C++

    In this exercise, you will develop a simple ATM simulator in C++ that logs every transaction to a file. Logging is a vital component in real-world applications, especially in banki...

  • Read and Display a Text File Using C++

    In this C++ exercise, you will create a program that reads the contents of a text file and prints them to the console. This task demonstrates how to work with file input streams in...

  • Register User Information and Save It to a File in C++

    In this C++ exercise, you will create a program that collects basic user information—specifically, their name and age—and writes it into a text file. This task introduces you to fi...

  • Count Words in a Text File Using C++

    In this exercise, you will write a C++ program that reads a text file and counts the total number of words contained in it. This task will help you become familiar with file input ...