139
stringstream parser;

parser << 5;
short top = 0;
parser >> top;
parser.str(""); //HERE I'M RESETTING parser

parser << 6; //DOESN'T PUT 6 INTO parser
short bottom = 0;
parser >> bottom;

Why doesn't it work?

Antonio Pérez
  • 6,702
  • 4
  • 36
  • 61
There is nothing we can do
  • 23,727
  • 30
  • 106
  • 194

1 Answers1

268

Typically to 'reset' a stringstream you need to both reset the underlying sequence to an empty string with str and to clear any fail and eof flags with clear.

parser.str( std::string() );
parser.clear();

Typically what happens is that the first >> reaches the end of the string and sets the eof bit, although it successfully parses the first short. Operations on the stream after this immediately fail because the stream's eof bit is still set.

Kinch
  • 21
  • 3
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • yes, it sets eof after operator>>() has been used and sometimes eof can set fail as well. Thanks – There is nothing we can do May 17 '10 at 10:10
  • 26
    Personally I think `parser.str("")` is clearer, but that's a matter of opinion. – T.E.D. May 17 '10 at 10:14
  • 7
    Might be worth editing this answer to put parser.clear() first, as other methods of adding content to the stream (e.g. parser << 5) don't work unless clear is called first. – John Doucette Feb 20 '14 at 22:13
  • 2
    @T.E.D. , I think it is a bit more efficient this way, since you avoid calling string constructor on a `const char *` – Moha the almighty camel Sep 07 '15 at 13:05
  • 2
    @Mhd.Tahawi - There are some cases, particularly those involving things that are inherently slow like resizing/destructing dynamically allocated containers, where it would be the height of folly to do the less clear thing for the sake of some theoretical micro-optimization. – T.E.D. Sep 07 '15 at 16:47
  • 10
    `parser.str({});` – v.oddou May 22 '19 at 05:40