【问题标题】:Resetting output flags in C++在 C++ 中重置输出标志
【发布时间】:2015-01-31 23:02:08
【问题描述】:

我打算在使用resetiosflags 函数结束的行上将所有输出标志重置为默认值。当我尝试以这种方式执行此操作时,它会提供错误的输出,这与我的预期相反。

#include <iostream>
#include <iomanip>
using namespace std;
int
main()
{
    bool first;
    int second;
    long third;
    float fourth;
    float fifth;
    double sixth;

    cout << "Enter bool, int, long, float, float, and double values: ";
    cin >> first >> second >> third >> fourth >> fifth >> sixth;
    cout << endl;

// ***** Solution starts here ****
    cout << first << " " << boolalpha << first  << endl << resetiosflags;
    cout << second << " " << showbase << hex << second << " " << oct << second << endl << resetiosflags;
    cout << third << endl;
    cout << showpos << setprecision(4) << showpoint << right << fourth << endl << resetiosflags;
    cout << scientific << fourth << endl << resetiosflags;
    cout << setprecision(7) << left << fifth << endl << resetiosflags;
    cout << fixed << setprecision(3) << fifth << endl << resetiosflags;
    cout << third << endl;
    cout << fixed << setprecision(2) << fourth << endl << resetiosflags;
    cout << fixed << setprecision(0) << sixth << endl << resetiosflags;
    cout << fixed << setprecision(8) << fourth << endl << resetiosflags;
    cout << setprecision(6) << sixth << endl << resetiosflags;
// ***** Solution ends here ****

    cin.get();
    return 0;
}

我已知的替代方法是通过重述它们来单独取消标记它们,但这似乎是多余的。

【问题讨论】:

  • resetiosflags 是一个接受一个参数的函数。你不是在给它打电话——你是在打印它的地址。
  • @IgorTandetnik 鉴于我打算重置我在每个语句末尾打开的标志,我应该考虑什么方法?

标签: c++ iostream flags iomanip


【解决方案1】:
/*unspecified*/ resetiosflags( std::ios_base::fmtflags mask );

std::resetiosflags() 是一个用于out &lt;&lt; resetiosfloags( flags ) 等表达式的操作符。大概你正在做的是传递一个函数指针,它被std::operator&lt;&lt; 的重载选择,它接受一个布尔值并打印 1。

但是std::resetiosflags() 将格式标志作为无法控制精度的参数。 std::ios_base::boolalpha 不过可以:

std::cout << ... << std::resetiosflags(std::ios_base::boolalpha);

还有std::noboolalpha

std::cout << ... << std::noboolalpha;

但是,如果您需要将精度重置为默认值,您可以为此创建自己的操纵器。你也可以使用Boost IO State Saver

【讨论】:

    猜你喜欢
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 2015-09-29
    • 2011-07-21
    相关资源
    最近更新 更多