how to read stringstream with dynamic size?

11,764

You get the extra c at the end because you don't test whether the stream is still good after you perform the extraction:

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
}
Share:
11,764
thomast.sang
Author by

thomast.sang

Updated on September 15, 2022

Comments

  • thomast.sang
    thomast.sang over 1 year

    I wanted to experiment with stringstream for an assignment, but I'm a little confused on how it works. 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 ""

  • thomast.sang
    thomast.sang over 13 years
    Thanks, I guess my question should've been phrased as how to check the condition of the stream.
  • James McNellis
    James McNellis over 13 years
    This is still incorrect in the general case: if you are trying to extract an int and the next available characters in the buffer can't be read as an int, the extraction will fail.