2013-06-20 43 views
3

當我使用串流時,我的cpp程序正在做一些奇怪的事情。當我將字符串和字符串流的初始化放在與我使用它相同的塊中時,沒有任何問題。但是,如果我把它上面的一個街區,字符串流犯規輸出字符串正確cpp中的奇怪範圍

正確的行爲,該程序將打印每個標記用空格分隔:

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 

int main() { 

    while (true){ 
     //SAME BLOCK 
     stringstream line; 
     string commentOrLine; 
     string almostToken; 
     getline(cin,commentOrLine); 
     if (!cin.good()) { 
      break; 
     } 
     line << commentOrLine; 
     do{ 

      line >> almostToken; 
      cout << almostToken << " "; 
     } while (line); 
     cout << endl; 
    } 
    return 0; 
} 

不正確的行爲,只有程序打印第一inputline:

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 

int main() { 
    //DIFFERENT BLOCK 
    stringstream line; 
    string commentOrLine; 
    string almostToken; 
    while (true){ 
     getline(cin,commentOrLine); 
     if (!cin.good()) { 
      break; 
     } 
     line << commentOrLine; 
     do{ 

      line >> almostToken; 
      cout << almostToken << " "; 
     } while (line); 
     cout << endl; 
    } 
    return 0; 
} 

爲什麼會發生這種情況?

+0

它可能是沖洗問題? – Nick

回答

7

當您爲每行「創建並銷燬」stringstream時,它也會獲得fail狀態重置。

在將新內容添加到line之前,您可以通過添加line.clear();來解決該問題。