using unsetf with hex dec and octal numbers in C++

Viewed 282

I have a question about using unsetf. The below is an answer for getting correct input for formatted numbers.

Actually, You can force operator>> to get and properly interpret prefixes 0 and 0x. All you have to do is to remove default settings for std::cin:

std::cin.unsetf(std::ios::dec);
std::cin.unsetf(std::ios::hex);
std::cin.unsetf(std::ios::oct);

Now, when you input 0x1a you will receive 26.

I don't understand the last two unsetf commands for hex and oct. If I use the unsetf with dec only, I get the correct input, which I mean inputting 0x1a and receiving 26.

So what's the point of using unsetf for hex and dec?

1 Answers

I don't understand the last two unsetf commands for hex and oct

If the hex and oct flags have not been set previously, yes unsetting dec is sufficient:

std::cin.unsetf(std::ios::dec);
int n;
std::cin >> n;  // 0x1a
std::cout << n; // 26

(demo)

But, if those flags have been set previously, they might impact the parsing of your hex numbers:

std::cin.unsetf(std::ios::dec);    
int n;
std::cin >> n;  // 0x1a
std::cout << n; // 0

(demo)

So, if you want to let std::cin parse your number by guessing their base, you should unsetf hex, dec and oct.

Related