c++stdfixedcout

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


This is inside of a display function. I want to print the weight using 2 decimal points. Outside of this code block, I don't want setprecision to be in effect. For example, 777.555 and 444.2222 should display correctly.

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

Problem is, once I used fixed << setprecision, I can only reset it to a number like 5 or 6 and then get this:

777.555000
444.222200

Solution

  • You can save the previous flags and precision, and then restore them afterwards, eg:

    // 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);
    }