A. Gille
A. Gille

Reputation: 1048

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 !

Upvotes: 0

Views: 70

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409206

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;

Upvotes: 1

IGarFieldI
IGarFieldI

Reputation: 585

The std::dec sets the formatting of numbers in the stream for later use, in the same way that std::hex sets the formatting for the in-/output of i.

Upvotes: 1

Related Questions