13

When using cout, what is the default formatter defined in the <iomanip> header? In other words, once I've set my formatter to fixed using cout << fixed << setPrecision(2), how do I change it back? Or, what am I changing it back to?

Moshe
  • 57,511
  • 78
  • 272
  • 425

4 Answers4

16

The answer is std::defaultfloat in C++11. To achieve this in C++03 you can do

cout.unsetf(std::ios_base::floatfield);

See Really, what's the opposite of "fixed" I/O manipulator?

Community
  • 1
  • 1
rmp251
  • 5,018
  • 4
  • 34
  • 46
  • `cout.unsetf(std::ios_base::floatfield);` this working with C++11 but not `std::defaultfloat` – Abhishek Mane Jun 14 '21 at 15:03
  • and also `cout.unsetf(std::ios_base::floatfield);` why it only reverse the effect of `fixed` as it not include any keyword like `fixed` means why it not reset `precision` also – Abhishek Mane Jun 14 '21 at 16:24
5

The opposite of std::fixed is std::scientific.

(You find a nice list of manipulators in this great answer.)

Community
  • 1
  • 1
sbi
  • 219,715
  • 46
  • 258
  • 445
  • 2
    The default float and the scientific notation are different. It is not exactly "changing it back". – SOFe Jun 21 '19 at 11:25
1

You can use resetiosflags() to unset any flags.

Chad
  • 18,706
  • 4
  • 46
  • 63
  • Is there a "default" that I can set to? – Moshe Sep 14 '11 at 19:56
  • I believe the default is `std::ios::scientific`. – Chad Sep 14 '11 at 19:58
  • @Moshe: Unfortunately, there is no simple way to fully reset a stream. Even the most elaborate code I have seen to do that (by James Kanze, more than a decade ago) misses on some esoteric propertiesm, like `iword` and `pword`. (Of course, James was fully aware of the limitations.) You can, however, get pretty far with [`std::ios::flags()`](http://www.cplusplus.com/reference/iostream/ios_base/flags/). – sbi Sep 14 '11 at 20:04
  • 1
    The easiest way to reset a stream is to default construct it. In some cases it may make sense to format your output in an `ostringstream` and then just send the already formatted output to `cout` as a `std::string`. It may be more costly to do it this way (output is not usually a place where I spend a lot of time optimizing or investigating performance issues, as usually other hardware related concerns outweigh any performance decreases). – Chad Sep 14 '11 at 20:13
1

The opposite of std::fixed is std::scientific. That might do for you.

However, if you want to restore more flags, or if you need the previous state, instead of the default you can use better solutions:

  1. the std::resetiosflags manipulator lets you reset specific flags to their defaults;

  2. the two ios::flags functions let you save and restore the previous values of the format flags.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510