copyfmt.cpp 724 B

12345678910111213141516171819202122232425262728293031323334
  1. // https://cirosantilli.com/linux-kernel-module-cheat#cpp
  2. #include <cassert>
  3. #include <iomanip>
  4. #include <iostream>
  5. #include <sstream>
  6. int main() {
  7. constexpr float pi = 3.14159265359;
  8. std::stringstream ss;
  9. // Sanity check default print.
  10. ss << pi;
  11. assert(ss.str() == "3.14159");
  12. ss.str("");
  13. // Change precision format to scientific,
  14. // and restore default afterwards.
  15. std::ios ss_state(nullptr);
  16. ss_state.copyfmt(ss);
  17. ss << std::setprecision(2);
  18. ss << std::scientific;
  19. ss << pi;
  20. assert(ss.str() == "3.14e+00");
  21. ss.str("");
  22. ss.copyfmt(ss_state);
  23. // Check that cout state was restored.
  24. ss << pi;
  25. assert(ss.str() == "3.14159");
  26. ss.str("");
  27. }