Match printf formatting with iomanip

I have old C code that I am trying to reproduce in C ++. It uses printf modifiers: "% 06.02f".

I naively thought that iomanip was just as capable and did:

 cout << setfill('0') << setw(6) << setprecision(2) 

When I try to print the test number 123.456, printf gives:

123.46

But cout gives:

1.2 + E02

Is there anything I can do in iomanip to reproduce this, or should I revert to using printf ?

[ Live example ]

+7
c ++ floating-point printf cout modifiers
source share
2 answers

Three C format specifiers are mapped to the corresponding format settings in C ++ IOStreams:

  • %f β†’ std::ios_base::fixed (fixed-point notation) is usually set using out << std::fixed .
  • %e β†’ std::ios_base::scientific (scientific notation) is usually set using out << std::scientific .
  • %g β†’ the default parameter, usually set using out.setf(std::fmtflags(), std::ios_base::floatfield) or with C ++ 11 and later out << std::defaultfloat . The default formatting attempts to get the β€œbest” of other formats, assuming a fixed number of digits to be used.

The precision, width, and fill symbol match what you have already specified.

+2
source share

Try std::fixed :

 std::cout << std::fixed; 

Sets the floatfield flag for the str fixed stream.

If the floatfield parameter floatfield set to fixed , floating point values ​​are written using fixed-point notation: the value is represented exactly as many digits in the decimal part as defined by the precision field and without the exponential part.

+4
source share

All Articles