Your problem is that you share the formatting state with someone else. Obviously you can decide to track the changes and to correct them. But there is a saying: The best way to solve a problem is to prevent it from happening.
In your case, you need to have your own formatting state and to not share it with anyone else. You can have your own formatting state by using an instance of std::ostream
with the same underlying streambuf than 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);
// output that could modify fmt flags
std::cout.setf(std::ios::scientific);
std::cout.precision(1);
// ----
// output some floats with my format independently of what other code did
my_fmt << "my format: " << 1.234 << "\n";
// output some floats with the format that may impacted by other code
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 there: live