Really, what's the opposite of “fixed” I/O manipulator?

只谈情不闲聊 提交于 2021-02-09 05:43:52

问题


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?


回答1:


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;



回答2:


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.




回答3:


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;
}


来源:https://stackoverflow.com/questions/19035131/really-whats-the-opposite-of-fixed-i-o-manipulator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!