Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn off setf in c++?

Tags:

c++

setf

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!

like image 286
bffaf02 Avatar asked Jan 04 '23 16:01

bffaf02


2 Answers

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.

like image 68
Lightness Races in Orbit Avatar answered Jan 14 '23 01:01

Lightness Races in Orbit


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)
like image 45
Swift - Friday Pie Avatar answered Jan 14 '23 02:01

Swift - Friday Pie