2010-08-08 41 views
1

這是一個使用stringstream的示例程序。目標是接受來自用戶的行(標準輸入)並在單獨的行中打印每個單詞。是否可以直接從用戶(標準輸入)接受字符串流?

int main() 
{ 

    std::istringstream currentline; 
    std::string eachword; 
    std::string line; 

    // Accept line from the standard input till EOF is reached 
    while (std::getline(std::cin,line)) 
    { 
     currentline.str(line); // Convert the input to stringstream 
     while (currentline >> eachword) // Convert from the entire line to individual word 
     { 
      std::cout << eachword << std::endl; 
     } 
     currentline.clear(); 
    } 
    return 0; 
} 

我想知道,有一種方法,我能避免中間字符串變量(對象),線,直接存儲用戶輸入到currentline(istringstream對象)。

注意:

我知道,下面的解決方案已經。

while (std::cin >> eachword) 
{ 
    std::cout << eachword << std::endl; 
} 
+2

爲什麼不直接使用第二個解決方案? – 2010-08-08 17:38:32

+0

尼爾,這就是我打算做的事。 – user373215 2010-08-08 17:46:55

回答

1

std::getline需要一個字符串引用的說法,而這也正是它把已獲得的線,所以你當然無法避免的傳球這樣的論點(並且仍然使用該功能)。你可以優雅封裝的結構,如果你經常需要它 - 例如爲:

bool getline(std::istream& i, std::istringstream& current) 
{ 
    std::string line; 
    if (std::getline(i, line)) { 
     current.str(line); 
     return true; 
    } 
    return false; 
} 
+2

包封物,肯定? – 2010-08-08 17:58:34

+1

不錯的功能。但我相信,你打算把istream作爲一個參數,在這種情況下,if語句不應該是這樣的, if(std :: getline(i,line)) – user373215 2010-08-08 18:11:00

+0

@Neil和@nsivakr,你們都對,tx - +1,編輯修復 – 2010-08-08 20:32:22

0

如果你想簡化第一個解決方案,

while (currentline(line) >> eachword) 
+0

雅各布,當我嘗試,它甚至沒有編譯。 – user373215 2010-08-08 18:13:25

0

我假設你要不要使用一箇中間對象,以防止不必要的複製?

您可以通過明確設置流緩衝區緩衝區來實現相同的效果。

int main() 
{ 
    std::string line; 
    std::istringstream currentline; 
    std::string eachword; 

    // Accept line from the standard input till EOF is reached 
    while (std::getline(std::cin,line)) 
    { 
     // Set the buffer without copying. 
     currentline.clear(); 
     currentline.rdbuf()->pubsetbuf(&line[0], line.length()); 

     while (currentline >> eachword) 
     { 
      std::cout << eachword << std::endl; 
     } 
    } 
    return 0; 
} 

由於破壞的順序。您只需確保將istringstream在您用作緩衝區的對象之前銷燬。所以你需要重新安排main()的頂部的聲明以確保該行是首先創建的,因此最後會被銷燬(否則istringstream的析構函數有可能訪問一個free'ed對象的內存。

+0

喜歡這個解決方案,但是當我運行這個程序的時候,它沒有打印這個文字。 rds,內部while循環,每次都失敗。 – user373215 2010-08-08 18:49:26

+0

@nsivakr:固定。僅僅因爲你重置緩衝區並不意味着標誌被重置。添加回呼叫清除以重置標誌。 – 2010-08-08 19:32:12

+0

>我運行它時仍然不起作用。 – user373215 2010-08-08 19:52:50

相關問題