Turn off setf in C ++?

I use setf to display decimal places in the output.

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

However, when I put the above code before exiting, other exits also affect it. Is there a way to use setf for only one output? How to disable it?

Thank you very much!

+4
source share
3 answers

setf returns the original value of the flag, so you can just save it and then return it when you're done.

The same goes for precision.

So:

// Change flags & precision (storing original values)
const auto original_flags     = std::cout.setf(std::ios::fixed | std::ios::showpoint);
const auto original_precision = std::cout.precision(2);

// Do your I/O
std::cout << someValue;

// Reset the precision, and affected flags, to their original values
std::cout.setf(original_flags, std::ios::fixed | std::ios::showpoint);
std::cout.precision(original_precision);

Read some documentation .

+6
source

You can use the flags () method to save and restore all flags or unsetf () returned by setf

 std::ios::fmtflags oldFlags( cout.flags() );

 cout.setf(std::ios::fixed);
 cout.setf(std::ios::showpoint);
 std::streamsize oldPrecision(cout.precision(2));

 // output whatever you should.

 cout.flags( oldFlags );
 cout.precision(oldPrecision)
+2

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);

// 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: live

+1
source

Source: https://habr.com/ru/post/1667442/


All Articles