user109078
user109078

Reputation: 906

Unexpected difference in iostream behavior between visual studio 2010 and gcc/g++ 4.6.3

Consider the following code snippet:

ofstream o("myFile.txt");

o.precision(14);
o.width(20);
o.setf(ios::showpoint);
o.setf(ios::internal);
o.fill(' ');

double zero = 0.0;

o << zero;

The results are:

0.00000000000000 //Visual studio 2010

0.0000000000000 //g++

Is this difference acceptable, or is it a bug in one of the compilers?

Upvotes: 3

Views: 92

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117906

The documentation for precision reads (emphasis mine):

The floating-point precision determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether the floatfield format flag is set to a specific notation (either fixed or scientific) or it is unset (using the default notation, which is not necessarily equivalent to either fixed nor scientific).

For the default locale:

  • Using the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum, and therefore it does not pad the displayed number with trailing zeros if the number can be displayed with less digits than the precision.

  • In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The digits before the decimal point are not relevant for the precision in this case.

It sounds like the compilers use different format flags.

Upvotes: 4

Related Questions