Use C++20 std::format and {:.2} instead of std::setprecision
Finally, this will be the superior choice once you can use it:
#include <format>
#include <string>
int main() {
    std::cout << std::format("{:.3} {:.4}\n", 3.1415, 3.1415);
}
Expected output:
3.14 3.145
This will therefore completely overcome the madness of modifying std::cout state.
The existing fmt library implements it for before it gets official support: https://github.com/fmtlib/fmt Install on Ubuntu 22.04:
sudo apt install libfmt-dev
Modify source to replace:
- <format>with- <fmt/core.h>
- std::formatto- fmt::format
main.cpp
#include <iostream>
#include <fmt/core.h>
int main() {
    std::cout << fmt::format("{:.3} {:.4}\n", 3.1415, 3.1415);
}
and compile and run with:
g++ -std=c++11 -o main.out main.cpp -lfmt
./main.out
Output:
3.14 3.142
See also:
Pre C++20/fmt::: Save the entire state with std::ios::copyfmt
You might also want to restore the entire previous state with std::ios::copyfmt in these situations, as explained at: Restore the state of std::cout after manipulating it
main.cpp
#include <iomanip>
#include <iostream>
int main() {
    constexpr float pi = 3.14159265359;
    constexpr float e  = 2.71828182846;
    // Sanity check default print.
    std::cout << "default" << std::endl;
    std::cout << pi << std::endl;
    std::cout << e  << std::endl;
    std::cout << std::endl;
    // Change precision format to scientific,
    // and restore default afterwards.
    std::cout << "modified" << std::endl;
    std::ios cout_state(nullptr);
    cout_state.copyfmt(std::cout);
    std::cout << std::setprecision(2);
    std::cout << std::scientific;
    std::cout << pi << std::endl;
    std::cout << e  << std::endl;
    std::cout.copyfmt(cout_state);
    std::cout << std::endl;
    // Check that cout state was restored.
    std::cout << "restored" << std::endl;
    std::cout << pi << std::endl;
    std::cout << e  << std::endl;
    std::cout << std::endl;
}
GitHub upstream.
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
default
3.14159
2.71828
modified
3.14e+00
2.72e+00
restored
3.14159
2.71828
Tested on Ubuntu 19.04, GCC 8.3.0.