首页 文章

如何更改此标记化过程以处理具有多行的文本文件?

提问于
浏览
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结束; 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);

          }

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

    如果您需要的只是流中的所有单词,并且没有每行处理,您实际上不需要首先在字符串中读取一行 . 只需像在代码中一样直接从其他流中读取 . 它不仅会读取一行中的单词,还会读取整个流中的单词,直到文件结尾:

    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++ Standard library是一本好书 .

相关问题