简体   繁体   English

如何读取动态大小的stringstream?

[英]how to read stringstream with dynamic size?

I wanted to experiment with stringstream for an assignment, but I'm a little confused on how it works. 我想尝试使用stringstream进行分配,但我对它的工作原理有点困惑。 I did a quick search but couldn't find anything that would answer my question. 我做了一个快速搜索,但找不到任何能回答我问题的东西。

Say I have a stream with a dynamic size, how would I know when to stop writing to the variable? 假设我有一个动态大小的流,我怎么知道何时停止写入变量?

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

 ss << var;

 while(ss){
  ss >> var;
  cout << var << endl;
 }

and my output would be: 我的输出将是:

2  
++  
asdf  
3  
*  
c  
c  

I'm not sure why I get that extra 'c' at the end, especially since _M_in_cur = 0x1001000d7 "" 我不知道为什么我最后得到额外的'c',特别是因为_M_in_cur = 0x1001000d7“”

You get the extra c at the end because you don't test whether the stream is still good after you perform the extraction: 最后得到额外的c ,因为在执行提取后,您不测试流是否仍然良好:

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

You need to test the stream state between when you perform the extraction and when you use the result. 您需要在执行提取和使用结果之间测试流状态。 Typically this is done by performing the extraction in the loop condition: 通常,这是通过在循环条件下执行提取来完成的:

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

The while(ss) condition check in your code checks if the last read from the stream was successful or not. 代码中的while(ss)条件检查检查流中的最后一次读取是否成功。 However, this check is going to return true even when you have read the last word in your string. 但是,即使您已读取字符串中的最后一个单词,此检查也将返回true。 Only the next extraction of ss >> var in your code is going to make this condition false since the end of the stream has been reached & there is nothing to extract into the variable var. 只有在代码中下一次提取ss >> var才会使这个条件成为错误,因为已经到达了流的末尾并且没有任何内容可以提取到变量var中。 This is the reason you get an extra 'c' at the end. 这就是你最后获得额外'c'的原因。 You can eliminate this by changing your code as suggested by James McNellis. 您可以通过更改James McNellis建议的代码来消除此问题。

There is also a member function good() which tests if the stream can be used for I/O operations. 还有一个成员函数good(),它测试流是否可用于I / O操作。 So using this the above code can be changed into 所以使用这个代码可以改成

while(ss.good())  // check if the stream can be used for io
{
    ss >> var;    // attempt extraction          <-- the stream state is set here
    cout << var;  // use result of extraction
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM