What's the best way (if any) to format std::*stream
output in localized manner, so that formatting changes in one location won't affect the use of that stream in other locations?
That is, I'd like to set format of the stream for a single statement, not for the remaining lifetime of the stream.
The following is just a rationale for asking the above question.
Suppose you print intensity in default floating point format:
ostringstream oss;
oss << "Intensity = " << intensity << "; ";
Then print coordinates with fixed 2 digits precision:
oss << "Point = (" << fixed << setprecision(2) << pt.x << ", " << pt.y << "); ";
then, 20 lines later, print ray direction in the same fixed 2 digits format:
oss << "Direction = (" << dir.x << ", " << dir.y << "); ";
A few months later add printing of luminosity in default floating point format somewhere between printing pt
and printing dir
:
oss << "Luminosity = " << lum << "; ";
Oops, lum
will be printed in fixed 2 digits precision because you changed oss
format 20 lines before, when printing pt
. Now you have to recall what you've changed in oss
and rewind it for printing lum
.
Moreover, after fixing format for lum
you'd get another problem: dir
won't be printed in fixed 2 digits anymore...
Therefore I'd like to be able to format streams locally to avoid unnecessary dependencies.