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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With