Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the width of the exponent field for an ostream?

Tags:

c++

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)?

like image 242
andreas buykx Avatar asked Nov 06 '08 13:11

andreas buykx


2 Answers

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
like image 90
Pieter Avatar answered Sep 29 '22 16:09

Pieter


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.

like image 24
xtofl Avatar answered Sep 29 '22 17:09

xtofl