Grupo
Manejo de Archivos en C++
Ojetivo
1. Cree un archivo de texto (p. ej., "data.txt") con varias líneas de texto sin ordenar.
2. Use `ifstream` para abrir y leer todas las líneas del archivo en un `vector`.
3. Use la función `sort()` del STL para ordenar las líneas alfabéticamente.
4. Muestre las líneas ordenadas en la consola.
5. Asegúrese de que el manejo de archivos y la comprobación de errores sean correctos en todo el programa.
Escriba un programa que ordene las líneas de un archivo de texto.
Ejemplo de Código C++
Mostrar Código C++
#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
}
Salida
Sorted lines from the file:
Apple
Banana
Carrot
Mango
Orange
Comparte este ejercicio C++