Really, what's the opposite of "fixed" I/O manipulator?
Asked Answered
A

3

5

This may be a duplicate of this question, but I don't feel it was actually answered correctly. Observe:

#include <iostream>
#include <iomanip>
using namespace std;
int main () {
  float p = 1.00;
  cout << showpoint << setprecision(3) << p << endl;
}

Output: 1.00

Now if we change that line to:

  cout << fixed << showpoint << setprecision(3) << p << endl;

we get: 1.000

And if we use the "opposite" of fixed we get something totally different:

  cout << scientific << showpoint << setprecision(3) << p << endl;

Output: 1.000e+00

How can I go back to the behaviour of the first version after fixed has been set?

Almatadema answered 26/9, 2013 at 17:48 Comment(0)
C
6

The format specification for floating points is a bitmask call std::ios_base::floatfield. In C++03 it has two named settings (std::ios_base::fixed and std::ios_base::scientific). The default setting is to have neither of these flags set. This can be achieved, e.g., using

stream.setf(std::ios_base::fmtflags(), std::ios_base::floatfield);

or

stream.unsetf(std::ios_base::floatfield);

(the type of the field is std::ios_base::fmtflags).

With the current C++ there is also std::ios_base::hexfloat and there are two manipulators added, in particular std::defaultfloat() which clears the std::ios_base::floatfield:

stream << std::defaultfloat;
Clipfed answered 26/9, 2013 at 17:55 Comment(0)
A
3

I think the answer is std::defaultfloat. However, this is only available in C++11. See http://en.cppreference.com/w/cpp/io/manip/fixed.

Almatadema answered 26/9, 2013 at 17:49 Comment(0)
R
0

Before C++11, you can clear the fixed flag, but not with a manipulator:

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    float p = 1.00;
    cout << showpoint << fixed << setprecision(3) << p << endl;

    // change back to default:
    cout.setf(0, ios::fixed);
    cout << showpoint << setprecision(3) << p << endl;
}
Reptant answered 26/9, 2013 at 17:55 Comment(1)
This doesn't seem to work for me (invalid conversion from 'int' to 'std::ios_base::fmtflags {aka std::_Ios_Fmtflags}' [-fpermissive])Almatadema

© 2022 - 2024 — McMap. All rights reserved.