Search code examples
c++iostreammanipulators

Meaning of trailing stream manipulator in C++ expression


What is the difference between both expressions of each pair ? I don't understand the effect of the trailing std::dec at the end of those expressions.

With cin, between this :

int i;
std::cin >> std::hex >> i >> std::dec;

and this :

int i;
std::cin >> std::hex >> i;

Same question with cout, between this :

int i;
std::cout << std::hex << i << std::dec << std::endl;

and this :

int i;
std::cout << std::hex << i << std::endl;

Thanks !


Solution

  • Some flags set by manipulators are only active for the next output or input operation.

    Others, like the formatting flags set by std::hex or std::dec are set permanently in the stream object, and affects all output and input operations after setting the flag.

    So if you use std::hex then all integer output and input from that point will be in hexadecimal notation. If you just want to output or input a single number in hexadecimal then you need to "reset" to the default decimal notation using e.g. std::dec leading to statements like

    std::cin >> std::hex >> i >> std::dec;