tags:

views:

115

answers:

3

This code:

#include <iostream>
int main( int, char **argv )
{
std::cout << 1.23e45 << std::endl;
}

prints

1.23e+045

when compiled with MS Visual Studio 2003, and

1.23e+45

on my Linux machine.

How can I specify the width of the exponent field (and why is there a difference in the first place)?

A: 

Look into the iomanip header. It has a lot of width-precision etc... functionality.

xtofl
Which one do I need? the width is the full width, the precision is the number of digits of the mantissa.
andreas buykx
as far as I know it's not possible with default iomanip attributes, as you said, both precision and width do something else...
Pieter
@Pieter: I propose you file that as an Answer, although it is not the answer that I was hoping for =-(
andreas buykx
+1  A: 

I don't think this is possible with standard manipulators. (if it is, I'd love to be corrected and learn how)

Your only remaining option is creating a streambuf yourself, and intercepting all exponent numbers that go to the stream, reformat them by hand, and pass them on to the underlying stream.

Seems a lot of work, and while not rocket science, no trivial task either.

On the 'why' question: I know linux defines the exponent as minimum two digits, I suppose Windows specifies it as minimum three?

// on linux
std::cout << std::scientific << 1.23e4 << std::endl

Also adds a leading zero:

1.230000e+04
Pieter
+1  A: 

As a follow-up of @Pieter's answer, I've been looking inside the operator<< (ostream&, double). Indeed, there is no field to specify the significance or width of the exponent. On windows, the operator<< forwards to sprintf, which has no exponent-size either.

In it's turn, the sprintf function (on Windows) calls into _cfltcvt_l, a function we have no source code for, but whose signature doesn't provide for an exponent-precision.

I know nothing of the implementation on Linux.

xtofl