Matching printf Formatting with iomanip
Asked Answered
A

2

7

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]

Alberich answered 14/12, 2015 at 20:0 Comment(2)
Try taking a look at boost::format(). It supports printf() type syntax for iostreams and is type safe.Kronick
@JonTrauntvein While I appreciate the tip (especially since tons of stuff in boost eventually makes it's way into the standard) I don't include boost wherever possible. And here it seems possible not to include it.Alberich
K
2

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

  • %f -> std::ios_base::fixed (fixed point notation) typically set using out << std::fixed.
  • %e -> std::ios_base::scientific (scientific notation) typically set using out << std::scientific.
  • %g -> the default setting, typically set using out.setf(std::fmtflags(), std::ios_base::floatfield) or with C++11 and later out << std::defaultfloat. The default formatting is trying to yield the "best" of the other formats assuming a fixed amount of digits to be used.

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

Kimball answered 14/12, 2015 at 20:6 Comment(0)
M
4

Try std::fixed:

std::cout << std::fixed;

Sets the floatfield format flag for the str stream to fixed.

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

Misbehave answered 14/12, 2015 at 20:1 Comment(2)
Yup, that got it, what's the meaning of fixed in this context?Alberich
@JonathanMee It uses fixed notation. I updated the post.Misbehave
K
2

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

  • %f -> std::ios_base::fixed (fixed point notation) typically set using out << std::fixed.
  • %e -> std::ios_base::scientific (scientific notation) typically set using out << std::scientific.
  • %g -> the default setting, typically set using out.setf(std::fmtflags(), std::ios_base::floatfield) or with C++11 and later out << std::defaultfloat. The default formatting is trying to yield the "best" of the other formats assuming a fixed amount of digits to be used.

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

Kimball answered 14/12, 2015 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.