FrozenHeart
FrozenHeart

Reputation: 20756

std::ostringstream and flush member function

Why so many people use flush() member function for std::ostringstream objects in situations like this:

#include <iostream>
#include <sstream>

int main()
{
   float f = 12.345f / 100;
   std::ostringstream ios;
   ios << f;
   ios.flush();
   std::cout << f << " : " << ios.str() << std::endl;
}

Output without this call will be the same.

So, why? And when should i use flush() member function?

Upvotes: 1

Views: 938

Answers (1)

john
john

Reputation: 87956

There is no good reason to use flush in that situation. I'd be interested to know where these so many people are. Personally I can't recall ever seeing flush used like that.

Most of the time I would put code like that down to superstition. Someone had a bug, which they never understood, but they tried flush and mysteriously the bug went away. Using flush wasn't the real reason the bug went away but it's use stuck.

You should use flush on a buffered stream when you want to buffered data to be output immediately.

Upvotes: 3

Related Questions