2009-01-27 14 views
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)){} 

得到循环运行。

但我不认为这会工作:

而(函数getline(streamOfText,readTextLine)){ COUT < < readTextLine < < ENDL;

//从字符串 的std :: stringstream的的strstr(readTextLine)构建体的流;

//使用流迭代器将流复制到向量中作为空白分隔字符串 std :: istream_iterator it(strstr); std :: istream_iterator end; std :: 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); 

      } 
+0

那么,有什么问题呢?你的解决方案对我来说很好。只需使用readTextLine作为stringstream构造函数的参数,并将所有代码包装到循环中即可。你面对什么问题? – 2009-01-27 21:42:31

+0

包装循环中的代码..我应该在哪里放置它? 的std :: istream_iterator 它(的strstr); std :: istream_iterator end; std :: vector results(it,end); – andandandand 2009-01-27 21:48:11

回答

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是一本好书。

相关问题