真的,什么是“固定”的I/O操作符的相反物?

5

这可能是 这个问题 的重复,但是我感觉它没有得到正确的答案。请注意:

#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 被设置后,我如何回到第一个版本的行为?

3个回答

6
浮点数的格式规范是一个位掩码调用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;

3

0

在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]) - rmp251

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接