2013-06-20 41 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();来解决该问题。