If I need to print a floating point number x I normally use printf("%g", x) as this is the simplest and the most convenient, for me, way to output floating point number in human-readable format where possible and automatically switch to exponential form for too large or too small values.
With std::cout and similar output streams it is not that simple. Say, I have class point_2d which overloads operator<< without changing stream's settings. E.g.:
ostream& operator<<(ostream& os, const point_2d& p)
{
os << '(' << p.x << "; " << p.y << ')';
return os;
}
If I do
std::cout << point_2d_instance << std::endl;
the output will be in whatever format was set for std::cout by this point.
I cannot change operator<< implementation and I do not know the current state of std::cout. Which flags should I set in std::cout to get an equivalent of
printf("(%g; %g)", p.x, p.y);
std::defaultfloator the default.If you depend on a particular format when working with streams operator, you should store the flags set on the stream, set your own flags, then restore original flags.