Contar palabras en un archivo de texto usando C++

En este ejercicio, escribirás un programa en C++ que lee un archivo de texto y cuenta el número total de palabras que contiene. Esta tarea te ayudará a familiarizarte con las operaciones de entrada de archivos mediante la clase `ifstream` y la manipulación de cadenas con la clase `stringstream`. Aprenderás a procesar un archivo línea por línea y a tokenizar cada línea para contar las palabras individualmente. Este ejercicio es útil para crear herramientas como analizadores de texto básicos o utilidades que procesan datos textuales.

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

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

Más ejercicios de programación C++Manejo de Archivos en C++

¡Explora el conjunto de ejercicios de programación en C++! Diseñados específicamente para principiantes, estos ejercicios te ayudarán a desarrollar una sólida comprensión de los fundamentos de C++. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte gradualmente a medida que adquieres confianza en la programación en C++.