fork download
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. /** provides a helper class to work with streams.
  5.  *
  6.  * It stores current format states of a stream in constructor and
  7.  * recovers these settings in destructor.
  8.  *
  9.  * Example:
  10.  * <pre>
  11.  * { // backup states of std::cout
  12.  * IOSFmtBackup stateCOut(std::cout);
  13.  * // do some formatted output
  14.  * std::cout
  15.  * << "dec: " << std::dec << 123 << std::endl
  16.  * << "hex: " << std::hex << std::setw(8) << std::setfill('0')
  17.  * << 0xdeadbeef << std::endl;
  18.  * } // destruction of stateCOut recovers former states of std::cout
  19.  * </pre>
  20.  */
  21. class IOSFmtBackup {
  22.  
  23. // variables:
  24. private:
  25. /// the concerning stream
  26. std::ios &_stream;
  27. /// the backup of formatter states
  28. std::ios _fmt;
  29.  
  30. // methods:
  31. public:
  32. /// @name Construction & Destruction
  33. //@{
  34.  
  35. /** constructor.
  36.   *
  37.   * @param stream the stream for backup
  38.   */
  39. explicit IOSFmtBackup(std::ios &stream):
  40. _stream(stream), _fmt(0)
  41. {
  42. _fmt.copyfmt(_stream);
  43. }
  44.  
  45. /// destructor.
  46. ~IOSFmtBackup() { _stream.copyfmt(_fmt); }
  47.  
  48. // disabled:
  49. IOSFmtBackup(const IOSFmtBackup&) = delete;
  50. IOSFmtBackup& operator=(const IOSFmtBackup&) = delete;
  51. //@}
  52. };
  53.  
  54. int main()
  55. {
  56. { // backup states of std::cout
  57. IOSFmtBackup stateCOut(std::cout);
  58. // do some formatted output
  59. std::cout
  60. << "dec: " << std::dec << 123 << std::endl
  61. << "hex: " << std::hex << std::setw(8) << std::setfill('0')
  62. << 0xdeadbeef << std::endl
  63. << "123 in current: " << 123 << std::endl;
  64. } // destruction of stateCOut recovers former states of std::cout
  65. // check whether formatting is recovered
  66. std::cout << "123 after recovered: " << 123 << std::endl;
  67. return 0;
  68. }
Success #stdin #stdout 0s 4452KB
stdin
Standard input is empty
stdout
dec: 123
hex: deadbeef
123 in current: 7b
123 after recovered: 123