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
Show 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