1

私はこのソースコードを使っています:

#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 end; std :: vector results(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);

          }
4

1 に答える 1

1

はい、では に 1 つの行全体があり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));
}

必要なのはストリームからのすべての単語であり、行ごとの処理がない場合は、実際には最初に行を文字列に読み込む必要はありません。コードで行ったように、他のストリームから直接読み取るだけです。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++ 標準ライブラリは良い本です。

于 2009-01-27T21:48:39.277 に答える