4

I am using setf in for displaying decimal places in outputs.

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

However, when I put the above code before an output, other outputs are affected too. Is there any way I can use setf for just only a single output? Like turning it off?

Thank you a lot!

4

3 回答 3

6

setf returns the original flag value, so you can simply store that then put it back when you're done.

The same is true of 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.

于 2017-01-21T17:36:20.547 回答
2

You can use flags() method to save and restore all flags or unsetf() the one 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)
于 2017-01-21T18:02:37.203 回答
1

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

于 2017-01-22T17:57:53.290 回答