What Pete said.
But, for a few dollars more, there is another way:
{ // main or function
{ // scope1
std:
stringstream sos;
sos << x << endl; // dec by default
sos << hex << x << endl; // hex
cout << sos.str() <<endl;} // scope1
cout << x << endl; // as normal (default)
}
Now you are not changing std::cout.
That's definitly the most certain. On the other hand, it's a
lot of extra effort, and rather heavy and cumbersome.
In case you can't do that, here is a short example:
{ // main of func
std::ios_base::fmtflags oldFlg =
cout.setf(std::ios_base::fixed, std::ios::floatfield);
int OutPre = cout.precision(40); // save prec, change to 40
// ------- use it here
// Case2Com Case2;
// Case2.execute(cout);
// -------
cout.setf( oldFlg, std::ios::floatfield ); // reset what you need
cout.precision( OutPre ); // restore orig precision
}
Here you pay another price, you need to 'reset' everything you changed.
This doesn't solve the problem. What happens if there is an
exception when you are using it? I thought everyone used RAII
here, and had their own SaveFormat or whatever class, so that
you'd write:
SaveFormat saver( std::cout ) ;
// whatever...
and when the destructor of saver was called, the original format
would be restored.
It's probably also worth pointing out that it is relatively
simple to use classes as manipulators, and restore the format in
their destructor. And of course, that in general, you don't use
the standard manipulators much in application code anyway; you
define your own, with application specific semantics, and do
logical formatting, instead of physical. (That way, when
someone decides that you need to output an additional digit in
degrees, you just change the manipulator for degrees, rather
than having to find which setprecision in you code refer to
degrees, and which don't.)
I have examples of both IOSave (a very, very old format saver)
and some useful manipulators (FFmt, EFmt and HexFmt) which
restore state at the end of the full expression at my site
(
http://kanze.james.neuf.fr/code-en.html; the above mentionned
classes are in the IO subsystem).