이 토큰 화 프로세스를 여러 줄의 텍스트 파일에서 작업하기 위해 어떻게 변경합니까?

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

  •  20-08-2019
  •  | 
  •  

문제

이 소스 코드를 중단하고 있습니다.

#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);
}

단일 줄을 토큰 화하고 벡터 결과에 넣는 대신이 텍스트 파일에서 가져온 줄 그룹을 토큰 화하고 결과 단어를 단일 벡터에 넣습니다.

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.

지금까지 나는

while (getline(streamOfText, readTextLine)){} 

루프를 실행합니다.

그러나 나는 이것이 효과가 없다고 생각합니다.

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

// 문자열에서 스트림을 구성하십시오 std :: stringstream strstr (readTextLine);

// 스트림 반복자를 사용하여 스트림을 벡터에 벡터에 복사하여 분리 된 문자열 std :: istream_iterator it (strstr); std :: istream_iterator 끝; STD :: 벡터 결과 (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);

          }
도움이 되었습니까?

해결책

예, 그럼 당신은 하나의 라인이 있습니다 readTextLine. 그 루프에서 원하는 것이 무엇입니까? 그런 다음 istream 반복기에서 벡터를 구성하는 대신 벡터로 복사하고 루프 외부의 벡터를 정의합니다.

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));
}

필요한 모든 것이 스트림의 모든 단어와 선별 처리가없는 경우 실제로 문자열에 줄을 읽을 필요가 없습니다. 코드에서했던 것처럼 직접 다른 스트림에서 읽으십시오. 그것은 한 줄에서 단어를 읽을뿐만 아니라 전체 스트림에서 파일 끝까지 :

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

의견에서 요구하는 것처럼 모든 것을 수동으로 수행하려면

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

나는 이것에 대한 좋은 책을 읽는 것이 좋습니다. 그것은 내가 생각하는 훨씬 더 유용한 기술을 보여줄 것입니다. C ++ 표준 라이브러리 Josuttis는 좋은 책입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top