如何读取动态大小的stringstream?

tho*_*ang 9 c++ stringstream

我想尝试使用stringstream进行分配,但我对它的工作原理有点困惑.我做了一个快速搜索,但找不到任何能回答我问题的东西.

假设我有一个动态大小的流,我怎么知道何时停止写入变量?

 string var = "2 ++ asdf 3 * c";
 stringstream ss;

 ss << var;

 while(ss){
  ss >> var;
  cout << var << endl;
 }
Run Code Online (Sandbox Code Playgroud)

我的输出将是:

2  
++  
asdf  
3  
*  
c  
c  
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我最后得到额外的'c',特别是因为_M_in_cur = 0x1001000d7""

Jam*_*lis 22

最后得到额外的c,因为在执行提取后,您不测试流是否仍然良好:

while (ss)        // test if stream is good
{
    ss >> var;    // attempt extraction          <-- the stream state is set here
    cout << var;  // use result of extraction
}
Run Code Online (Sandbox Code Playgroud)

您需要在执行提取和使用结果之间测试流状态.通常,这是通过在循环条件下执行提取来完成的:

while (ss >> var) // attempt extraction then test if stream is good
{
    cout << var;  // use result of extraction
}
Run Code Online (Sandbox Code Playgroud)