Only 2 digits in exponent in scientific ofstream
Asked Answered
S

5

5

So according to cplusplus.com when you set the format flag of an output stream to scientific notation via

of.setf(ios::scientific)

you should see 3 digits plus and a sign in the exponent. However, I only seem to get 2 in my output. Any ideas? Compiled on Mac OS using GCC 4.0.1.

Here's the actual code I am using:

of.setf(ios::scientific);
of.precision(6);
for (int i=0;i<dims[0];++i) {
    for (int j=0;j<dims[1];++j) {
    of << setw(15) << data[i*dims[1]+j];                    
    }
    of << endl;
}

and an example line of output:

   1.015037e+00   1.015037e+00   1.395640e-06  -1.119544e-06  -8.333264e-07

Thanks

Solita answered 10/8, 2009 at 20:59 Comment(0)
L
4

I believe cplusplus.com is incorrect, or at least is documenting a particular implementation - I can't see any other online docs which specifically state the number of exponent digits which are displayed - I can't even find it in the C++ specification.

Edit:

The C++ Standard Library: A Tutorial and Reference doesn't explicitly state the number of exponent digits; but all it's examples display two exponent digits.

Lycurgus answered 10/8, 2009 at 21:14 Comment(0)
B
4

It's implementation specific.

Blow answered 10/8, 2009 at 21:18 Comment(0)
F
1

This is a bug in M$ implementation AFAIK

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/624b679a4faf03d

Forereach answered 8/10, 2009 at 15:50 Comment(0)
R
0

I'm getting 3 in MSVC++08 and g++ 4.4.0 with this code:

#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <vector>

typedef float NumberType;

double generate_number(void)
{
    return static_cast<NumberType>(std::rand()) / RAND_MAX;
}

void print_number(NumberType d)
{
    std::cout << std::setw(15) << d << std::endl;
};

int main(void)
{
    std::vector<NumberType> data;

    std::generate_n(std::back_inserter(data), 10, generate_number);

    // print
    std::cout.setf(std::ios::scientific);
    std::cout.precision(6);
    std::for_each(data.begin(), data.end(), print_number);
}

You can easily change the number type it uses. It gives me three places with both float and double, and the standard says nothing on the actual formatting, so I'd go with mgb's answer.

Reprobate answered 10/8, 2009 at 21:21 Comment(2)
Same code compiled on OS X/Intel gives two exponent digits - looks pretty conclusive it's simply implementation-dependent.Lycurgus
@GMan: Always the way on SO ;)Lycurgus
S
0

I have just had a thought - since I am printing floats, why would it display 3 exponent values since the max/min exponent is ~38. I bet if the data array were type double there would be 3.

Solita answered 10/8, 2009 at 21:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.