我怎样才能只使用 fixed << setprecision(2) 一次?或者至少恢复到默认行为?

How can I use fixed << setprecision(2) only ONCE? Or at least restore to default behaviour?

这是在显示函数中。我想使用 2 个小数点打印重量。在这个代码块之外,我不希望 setprecision 生效。例如,777.555 和 444.2222 应该正确显示。

        // Detect if train has cargo:
        if (cargo_unit)
        {
            // If cargo exists, print output:
            cout << **fixed << setprecision(2);**
            cout << "   Cargo: " << cargo_unit->getDesc() <<
            endl << "  Weight: " << cargo_unit->getWeight() << endl;
        }

问题是,一旦我使用了 fixed << setprecision,我只能将它重置为 5 或 6 这样的数字,然后得到这个:

777.555000 444.222200

使用std::defaultfloat重置std::fixed

访问this link了解更多信息。

可以保存之前的flags和precision,之后再恢复,例如:

// Detect if train has cargo:
if (cargo_unit)
{
    // If cargo exists, print output:

    std::ios_base::fmtflags old_flags = cout.flags();
    std::streamsize old_prec = cout.precision();
    std::cout << std::fixed << std::setprecision(2);

    /* alternatively:
    std::ios_base::fmtflags old_flags = cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
    std::streamsize old_prec = cout.precision(2);
    */

    std::cout << "   Cargo: " << cargo_unit->getDesc() <<
    std::endl << "  Weight: " << cargo_unit->getWeight() << std::endl;

    cout.precision(old_prec);
    cout.flags(old_flags);
}

这是另一种方法,使用 std::cout.precision() 在将其更改为 2 之前保存默认精度,然后在需要时将其恢复为默认值。

...
// save current precision
std::streamsize ss = std::cout.precision();

// Detect if train has cargo:
if (cargo_unit)
{
    // If cargo exists, print output:
    cout << **fixed << setprecision(2);**
    cout << "   Cargo: " << cargo_unit->getDesc() <<
    endl << "  Weight: " << cargo_unit->getWeight() << endl;
}

// Restore saved precision
std::cout << std::setprecision(ss);
...