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!
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With