2009-01-27 13 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是一本好書。

相關問題