简体   繁体   中英

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

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM