¿Cómo modifico este proceso de tokenización para que funcione en un archivo de texto con varias líneas?

StackOverflow https://stackoverflow.com/questions/485371

  •  20-08-2019
  •  | 
  •  

Pregunta

Estoy trabajando este código fuente:

#include <string>
#include <vector>
#include <iostream>
#include <istream>
#include <ostream>
#include <iterator>
#include <sstream>
#include <algorithm>

int main()
{
  std::string str = "The quick brown fox";

  // construct a stream from the string
  std::stringstream strstr(str);

  // use stream iterators to copy the stream to the vector as whitespace separated strings
  std::istream_iterator<std::string> it(strstr);
  std::istream_iterator<std::string> end;
  std::vector<std::string> results(it, end);

  // send the vector to stdout.
  std::ostream_iterator<std::string> oit(std::cout);
  std::copy(results.begin(), results.end(), oit);
}

Para, en lugar de tokenizar una sola línea y ponerla en los resultados del vector, tokeniza un grupo de líneas tomadas de este archivo de texto y pone las palabras resultantes en un solo vector.

Text File:
Munroe states there is no particular meaning to the name and it is simply a four-letter word without a phonetic pronunciation, something he describes as "a treasured and carefully-guarded point in the space of four-character strings." The subjects of the comics themselves vary. Some are statements on life and love (some love strips are simply art with poetry), and some are mathematical or scientific in-jokes.

Hasta ahora, solo tengo claro que necesito usar un

while (getline(streamOfText, readTextLine)){} 

para ejecutar el bucle.

Pero no creo que esto funcione:

while (getline (streamOfText, readTextLine)) {                cout < < readTextLine < < endl;

// construye una secuencia desde la cadena   std :: stringstream strstr (readTextLine);

// usa iteradores de flujo para copiar el flujo al vector como cadenas separadas por espacios en blanco   std :: istream_iterator it (strstr);   std :: istream_iterator end;   std :: resultados del vector (it, end);

/*HOw CAN I MAKE THIS INSIDE THE LOOP WITHOUT RE-DECLARING AND USING THE CONSTRUCTORS FOR THE ITERATORS AND VECTOR? */

  // send the vector to stdout.
  std::ostream_iterator<std::string> oit(std::cout);
  std::copy(results.begin(), results.end(), oit);

          }
¿Fue útil?

Solución

Sí, entonces tiene una línea completa en readTextLine. ¿Es eso lo que querías en ese bucle? Luego, en lugar de construir el vector a partir de los iteradores istream, copie en el vector y defina el vector fuera del ciclo:

std::vector<std::string> results;
while (getline(streamOfText, readTextLine)){
    std::istringstream strstr(readTextLine);
    std::istream_iterator<std::string> it(strstr), end;
    std::copy(it, end, std::back_inserter(results));
}

En realidad, no necesita leer una línea en la cadena primero, si todo lo que necesita son todas las palabras de una secuencia, y sin procesamiento por línea. Simplemente lea la otra transmisión directamente como lo hizo en su código. No solo leerá palabras de una línea, sino de toda la secuencia, hasta el final del archivo:

std::istream_iterator<std::string> it(streamOfText), end;
std::vector<std::string> results(it, end);

Para hacer todo eso manualmente, como pide en los comentarios, haga

std::istream_iterator<std::string> it(streamOfText), end;
while(it != end) results.push_back(*it++);

Te recomiendo que leas un buen libro sobre esto. Le mostrará técnicas mucho más útiles, creo. La biblioteca estándar C ++ de Josuttis es un buen libro.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top