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 file contents is a common task in data processing and file manipulation. The program will utilize the Standard Template Library (STL), specifically `vector` to store lines and `sort()` to perform the sorting. This practice enhances your understanding of file input/output, dynamic containers like vectors, and the use of standard algorithms in C++.

Group

File Management in C++

Objective

1. Create a text file (e.g., "data.txt") with several lines of unsorted text.
2. Use `ifstream` to open and read all lines from the file into a `vector`.
3. Use the `sort()` function from the STL to sort the lines alphabetically.
4. Display the sorted lines on the console.
5. Ensure proper file handling and error checking throughout the program.

Write a program that sorts the lines of a text file.

Example C++ Exercise

 Copy C++ Code
#include <iostream>      // For input and output operations
#include <fstream>       // For file stream handling
#include <string>        // For using the string class
#include <vector>        // For using the vector container
#include <algorithm>     // For the sort function
using namespace std;

int main() {
    ifstream inFile("data.txt");     // Open the file for reading
    vector<string> lines;           // Vector to store all lines from the file
    string line;                      // Variable to hold each line

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

    // Read all lines from the file and store them in the vector
    while (getline(inFile, line)) {
        lines.push_back(line); // Add each line to the vector
    }

    inFile.close(); // Close the file after reading

    // Sort the lines alphabetically using STL sort
    sort(lines.begin(), lines.end());

    // Display the sorted lines
    cout << "Sorted lines from the file:" << endl;
    for (const string& sortedLine : lines) {
        cout << sortedLine << endl; // Print each sorted line
    }

    return 0; // End of program
}

 Output

Sorted lines from the file:
Apple
Banana
Carrot
Mango
Orange

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

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

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