c++floating-pointprintfcoutmodifiers

Matching printf Formatting with iomanip


I have some old C code I'm trying to replicate the behavior of in C++. It uses the 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 output the test number 123.456, printf yields:

123.46

But cout yields:

1.2+e02

Is there anything I can do in iomanip to replicate this, or must I go back to using printf?

[Live Example]


Solution

  • The three C format specifiers map to corresponding format setting in C++ IOStreams:

    The precision, the width, and the fill character match the way you already stated.