Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 378
Jonathan Mee Avatar asked Dec 14 '15 20:12

Jonathan Mee


People also ask

Can I use printf in C++?

It can be used in C++ language too. Here is the syntax of printf() in C and C++ language, printf(“string and format specifier”, variable_name);

What is %g in printf?

According to most sources I've found, across multiple languages that use printf specifiers, the %g specifier is supposed to be equivalent to either %f or %e - whichever would produce shorter output for the provided value.

What is %B in printf?

The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).


1 Answers

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.

like image 78
AlexD Avatar answered Oct 12 '22 13:10

AlexD