真的,"fixed" I/O 操纵器的反面是什么?

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

本文关键字:是什么 fixed 真的 操纵      更新时间:2023-10-16

这可能是这个问题的重复,但我觉得它实际上没有正确回答。观察:

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

输出:1.00

现在,如果我们将该行更改为:

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

我们得到:1.000

如果我们使用固定的"相反",我们会得到完全不同的东西:

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

输出:1.000e+00

设置fixed后如何返回到第一个版本的行为?

浮点的格式规范是位掩码调用std::ios_base::floatfield。在 C++03 中,它有两个命名设置(std::ios_base::fixedstd::ios_base::scientific )。默认设置是不设置这些标志。这可以实现,例如,使用

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

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

(字段类型为 std::ios_base::fmtflags )。

对于当前C++,还std::ios_base::hexfloat并且添加了两个机械手,特别是清除std::ios_base::floatfieldstd::defaultfloat()

stream << std::defaultfloat;
我认为

答案是std::defaultfloat.但是,这仅在 C++11 中可用。请参阅 http://en.cppreference.com/w/cpp/io/manip/fixed。

在 C++11 之前,您可以清除 fixed 标志,但不能使用操纵器:

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