どのように私は複数行のテキストファイルで作業するには、このトークン化プロセスを変更するのですか?

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

ループの実行を取得します。

しかし、私はこれがうまくいくとは思わない:

一方(のgetline(streamOfText、readTextLine)){                coutの<< readTextLine <<てendl;

//文字列からストリームを構築   std ::にstringstreamはstrstr(readTextLine);

//空白で区切られた文字列としてベクトルにストリームをコピーするには、ストリームのイテレータを使用   std :: istream_iteratorそれ(はstrstr)。   std :: istream_iteratorエンド。   std ::ベクトルの結果(それは、エンド);

/*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で1行全体を持っています。それはあなたがそのループに何を望むかということですか?代わりの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));
}
あなたが必要とするすべてのストリームからすべての単語、および無当りオンライン処理の場合は、

あなたは、実際に、最初の文字列に行を読む必要はありません。ちょうどあなたがあなたのコード内でやった直接のような他のストリームから読み取ります。それだけで1行から単語を読んではなくなり、全体の流れから、ファイルの終わりまで:

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

私はあなたがこの上で良い本を読むことをお勧めします。それはあなたに私は考えてはるかに有用な技術が表示されます。 Josuttis氏による C ++標準ライブラリの良い本です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top