c++setf

Turn off setf in c++?


I am using setf in for displaying decimal places in outputs.

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

However, when I put the above code before an output, other outputs are affected too. Is there any way I can use setf for just only a single output? Like turning it off?


Solution

  • setf returns the original flag value, so you can simply store that then put it back when you're done.

    The same is true of precision.

    So:

    // Change flags & precision (storing original values)
    const auto original_flags     = std::cout.setf(std::ios::fixed | std::ios::showpoint);
    const auto original_precision = std::cout.precision(2);
    
    // Do your I/O
    std::cout << someValue;
    
    // Reset the precision, and affected flags, to their original values
    std::cout.setf(original_flags, std::ios::fixed | std::ios::showpoint);
    std::cout.precision(original_precision);
    

    Read some documentation.