Your problem is that you are sharing the formatting state with someone else. Obviously, you can track changes and correct them. But there is a saying: the best way to solve the problem is to prevent it.
In your case, you need to have your own formatting state and not pass it on to anyone else. You can have your own formatting state using an instance std::ostreamwith the same underlying streambuf as std::cout.
std::ostream my_fmt(std::cout.rdbuf());
my_fmt.setf(std::ios::fixed);
my_fmt.setf(std::ios::showpoint);
my_fmt.precision(2);
std::cout.setf(std::ios::scientific);
std::cout.precision(1);
my_fmt << "my format: " << 1.234 << "\n";
std::cout << "std::cout format: " << 1.234 << "\n";
This will output:
my format: 1.23
std::cout format: 1.2e+00
See a live example: live
source
share