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 C++, using the standard `` library. You will learn how to open a file, check if it's successfully opened, and read it line by line. This type of file handling is fundamental for working with data persistence, logging, and external configurations in software development.

Group

File Management in C++

Objective

1. Include the necessary headers to handle file input.
2. Prompt the user to enter the name of the file to be read.
3. Use an ifstream object to open and read the file line by line.
4. Display each line of the file on the console.
5. Handle the case where the file cannot be opened.

Write a program that reads a text file and prints it to the console.

Example C++ Exercise

 Copy C++ Code
#include <iostream>      // Include for standard 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;     // Variable to store the file name
    string line;         // Variable to store each line from the file

    // Prompt the user to enter the file name
    cout << "Enter the name of the file to read: ";
    cin >> filename;     // Read the file name from the user

    ifstream inputFile(filename);  // Create an input file stream and open the file

    // Check if the file was successfully opened
    if (inputFile.is_open()) {
        cout << "Contents of the file:" << endl;

        // Read the file line by line and print each line
        while (getline(inputFile, line)) {
            cout << line << endl;  // Print the current line
        }

        inputFile.close();  // Close the file after reading
    } else {
        // If the file could not be opened, display an error message
        cout << "Error: Could not open the file." << endl;
    }

    return 0;  // End of the program
}

 Output

Enter the name of the file to read: sample.txt
Contents of the file:
This is a sample text file.
It contains multiple lines.
Each line is displayed in the console.

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

  • 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 ...

  • Copy File Contents Using C++

    This exercise involves writing a C++ program to copy the entire content of one file into another. By completing this task, you will practice using file streams in C++, specifically...

  • Find and Replace a Word in a File Using C++

    In this exercise, you will create a C++ program that searches for a specific word in a text file and replaces it with another word. This task will help you strengthen your understa...

  • Save and Load a List of Numbers from a File in C++

    In this exercise, you will create a C++ program that allows the user to input a list of numbers, save them to a text file, and then read and display those numbers from the file. Th...

  • 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 analyz...