Grupo
Manejo de Archivos en C++
Ojetivo
1. Abra un archivo de texto existente para leerlo con `ifstream`.
2. Lea el archivo línea por línea.
3. Para cada línea, use `stringstream` para extraer palabras.
4. Cuente el número total de palabras.
5. Muestre el recuento total en pantalla.
Implemente un programa que cuente las palabras en un archivo de texto.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include for standard input and output
#include <fstream> // Include for file input stream
#include <sstream> // Include for stringstream
#include <string> // Include for using the string class
using namespace std;
int main() {
ifstream file("sample.txt"); // Open the file 'sample.txt' for reading
string line; // Variable to hold each line from the file
int wordCount = 0; // Counter to track total number of words
// Check if the file was opened successfully
if (file.is_open()) {
// Read the file line by line
while (getline(file, line)) {
stringstream ss(line); // Create a stringstream for the current line
string word; // Variable to store individual words
// Extract words from the line
while (ss >> word) {
wordCount++; // Increment the word counter for each word
}
}
file.close(); // Close the file after reading
// Output the total number of words
cout << "Total number of words in the file: " << wordCount << endl;
} else {
// Display error message if file couldn't be opened
cout << "Error: Could not open file." << endl;
}
return 0; // End of program
}
Salida
//Output Example:
Total number of words in the file: 42
//Content of sample.txt (for reference):
This is a sample text file.
It contains several lines of words.
The program should count them all correctly.
Comparte este ejercicio C++