How to Restore the State of std::cout After Manipulating It
In C , manipulating the state of output streams such as std::cout allows for versatile formatting options. However, sometimes it becomes necessary to restore the original state after performing these alterations.
Consider the following code:
void printHex(std::ostream& x){ x << std::hex << 123; } int main(){ std::cout << 100; // prints 100 base 10 printHex(std::cout); //prints 123 in hex std::cout << 73; //problem! prints 73 in hex.. }
Here, after calling printHex, the state of std::cout changes to hexadecimal output. As a result, subsequent print operations also print in hexadecimal, even though the programmer may not desire this behavior.
To address this issue, one can utilize the following technique:
#include <iostream> std::ios_base::fmtflags f( cout.flags() ); // Your code here... cout.flags( f );
By saving the current flags (formatting options) of std::cout in the variable f before performing any manipulations, one can restore the original state by setting the flags back to f after the desired changes.
Alternatively, for more convenient and object-oriented code, one can employ RAII (Resource Acquisition Is Initialization) as follows:
#include <iostream> struct FlagsSaver { FlagsSaver() : flags( cout.flags() ) {} ~FlagsSaver() { cout.flags( flags ); } private: std::ios_base::fmtflags flags; }; void printHex(std::ostream& x) { FlagsSaver saver; // RAII to restore flags x << std::hex << 123; } int main() { std::cout << 100; // prints 100 base 10 printHex(std::cout); //prints 123 in hex std::cout << 73; // prints 73 base 10 (original flags restored) }
The above is the detailed content of How to Reset `std::cout` to its Original State After Formatting Changes?. For more information, please follow other related articles on the PHP Chinese website!