mirror of
https://github.com/cirosantilli/linux-kernel-module-cheat.git
synced 2026-01-23 02:05:57 +01:00
c++: copyfmt
This commit is contained in:
@@ -13834,6 +13834,8 @@ Programs under link:userland/cpp/[] are examples of https://en.wikipedia.org/wik
|
|||||||
** link:userland/cpp/template.cpp[]: basic example
|
** link:userland/cpp/template.cpp[]: basic example
|
||||||
** link:userland/cpp/template_class_with_static_member.cpp[]: https://stackoverflow.com/questions/3229883/static-member-initialization-in-a-class-template
|
** link:userland/cpp/template_class_with_static_member.cpp[]: https://stackoverflow.com/questions/3229883/static-member-initialization-in-a-class-template
|
||||||
** link:userland/cpp/if_constexpr.cpp[]: C++17 `if constexpr`
|
** link:userland/cpp/if_constexpr.cpp[]: C++17 `if constexpr`
|
||||||
|
* iostream
|
||||||
|
** link:userland/cpp/copyfmt.cpp[]: `std::copyfmt` restores stream state, see also: https://stackoverflow.com/questions/12560291/set-back-default-floating-point-print-precision-in-c/53673686#53673686
|
||||||
* fstream
|
* fstream
|
||||||
** link:userland/cpp/file_write_read.cpp[]
|
** link:userland/cpp/file_write_read.cpp[]
|
||||||
** link:userland/cpp/temporary_directory.cpp[]: illustrates `std::filesystem::temp_directory_path` and answers https://stackoverflow.com/questions/3379956/how-to-create-a-temporary-directory-in-c/58454949#58454949
|
** link:userland/cpp/temporary_directory.cpp[]: illustrates `std::filesystem::temp_directory_path` and answers https://stackoverflow.com/questions/3379956/how-to-create-a-temporary-directory-in-c/58454949#58454949
|
||||||
|
|||||||
33
userland/cpp/copyfmt.cpp
Normal file
33
userland/cpp/copyfmt.cpp
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
// https://cirosantilli.com/linux-kernel-module-cheat#cpp
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <iostream>
|
||||||
|
#include <sstream>
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
constexpr float pi = 3.14159265359;
|
||||||
|
|
||||||
|
std::stringstream ss;
|
||||||
|
|
||||||
|
// Sanity check default print.
|
||||||
|
ss << pi;
|
||||||
|
assert(ss.str() == "3.14159");
|
||||||
|
ss.str("");
|
||||||
|
|
||||||
|
// Change precision format to scientific,
|
||||||
|
// and restore default afterwards.
|
||||||
|
std::ios ss_state(nullptr);
|
||||||
|
ss_state.copyfmt(ss);
|
||||||
|
ss << std::setprecision(2);
|
||||||
|
ss << std::scientific;
|
||||||
|
ss << pi;
|
||||||
|
assert(ss.str() == "3.14e+00");
|
||||||
|
ss.str("");
|
||||||
|
ss.copyfmt(ss_state);
|
||||||
|
|
||||||
|
// Check that cout state was restored.
|
||||||
|
ss << pi;
|
||||||
|
assert(ss.str() == "3.14159");
|
||||||
|
ss.str("");
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user