Grupo
Manejo de Archivos en C++
Ojetivo
1. Cree o asegúrese de que exista un archivo de texto con varias líneas de contenido.
2. Use `ifstream` para abrir el archivo y leerlo.
3. Lea cada línea usando un bucle `while` y la función `getline()`.
4. Por cada línea leída, incremente un contador.
5. Al llegar al final del archivo, muestre el recuento total de líneas.
6. Cierre el archivo correctamente una vez finalizada la lectura.
Escriba un programa que calcule el número de líneas de un archivo de texto.
Ejemplo de Código C++
Mostrar Código C++
#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
}
Salida
The file contains 7 lines.
Comparte este ejercicio C++