2015-02-24 32 views
0

C++讀字和行,我明白如何尋找並從文本文件中讀取單詞。我也理解你如何使用getline()來瀏覽文本並閱讀某一行。在同一個閱讀循環

但現在我試圖找出如何在相同的「閱讀圈」同時使用。

這將是這樣的:

string S1="mysearchword01",S2="mysearchword02"; 
    char word[50]; 

    while(myfile.good()){ //while didn't reach the end line 

     file>>word; //go to next word 
     if (word==S1){ //if i find S1 I cout the two next words 
      file>>a>>b; 
      cout<<a<<" "<<b<<endl;} 
      } 
     else if (word==S2) { 
      //****here I want to cout or save the full line*****  
      } 
    } 

所以我可以用函數getline在那裏不知何故?

在此先感謝。

+1

'而(myfile.good())'這是錯誤的。它將在空文件上返回true。要讀取一行,請使用'string line; while(getline(myfile,line)){..}' – 2015-02-24 12:31:19

+0

while(myfile.good())正在爲我工​​作。如果我在沒有「else if」的情況下使用該代碼,它將逐字查找我的文本文件S1。如果它發現它會調出下兩個單詞。然後while循環在文件結束時停止。 – remi000 2015-02-24 12:34:24

+0

字應該是一個字符,而不是字符串,將編輯。 – remi000 2015-02-24 12:37:02

回答

0

std::fstream::good()檢查是否最後的I/O操作是成功的,並且,當它在你實現它的方式,它是不是真的是你想要的這裏。

使用getline(file, stringToStoreInto)代替在while循環中調用good(),它在到達文件結尾時也會返回false。

編輯:爲了從您std::getline()得到行一個空格分隔元素(字),你可以使用std::stringstream,用線串初始化,然後提取單個詞的是字符串流進入另一個「字「字符串使用>>運算符。

所以對於你的情況,像這樣的事:

#include <sstream> 

std::string line, word; 

while (getline(file, line)) 
{ 
    std::stringstream ss(line); 

    ss >> word; 

    if (word == S1) 
    { 
     // You can extract more from the same stringstream 
     ss >> a >> b; 
    } 

    else if (word == S2) 
    { 
     /* ... */ 
    } 
} 

另外,您也可以實例化的stringstream對象一次,並調用其str()方法,一個超載其中重置流,而其他重載替換其內容。

#include <sstream> 

std::stringstream ss; 

std::string line, word; 

while (getline(file, line)) 
{ 
    ss.str(line); // insert/replace contents of stream 

    ss >> word; 

    if (word == S1) 
    { 
     // You can extract more from the same stringstream 
     ss >> a >> b; 
    } 

    else if (word == S2) 
    { 
     /* ... */ 
    } 
} 

您可以使用字符串流中提取多個字,不只是第一個,只是不停地打電話operator>>像你以前那樣。

+0

好的,謝謝。但在這種情況下,單詞將是整個行?不是該行中的第一個單詞? – remi000 2015-02-24 12:42:07

+0

@ remi000字將在這裏整個行。如果你把它放在一個stringstream中,你可以提取實際的單詞。 – 2015-02-24 12:43:54

+0

是的,這是getline的目的。如果你想從那行中得到空格分隔的元素,你可以遵循Neil的建議,或者寫一些像Python的split()方法那樣的內置字符串分割函數。 – 2015-02-24 12:46:15