【问题标题】:Really, what's the opposite of "fixed" I/O manipulator?真的,与“固定”I/O 操纵器相反的是什么?
【发布时间】:2013-09-26 17:48:21
【问题描述】:

这可能与this question 重复,但我认为它实际上没有得到正确回答。观察:

#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 后,我怎样才能回到第一个版本的行为?

【问题讨论】:

    标签: c++ floating-point cout iomanip


    【解决方案1】:

    浮点的格式规范是位掩码调用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::defaultfloat() 清除了 std::ios_base::floatfield

    stream << std::defaultfloat;
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 这似乎对我不起作用(从 'int' 到 'std::ios_base::fmtflags {aka std::_Ios_Fmtflags}' [-fpermissive] 的无效转换)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        • 1970-01-01
        • 2017-05-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多