Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting hex through Cin

Tags:

c++

hex

Why doesn't this code work?

int x;
cin >> x;

With the input of 0x1a I get that x == 0 and not 26.

Why's that?

like image 415
Quaker Avatar asked Nov 02 '12 13:11

Quaker


2 Answers

I believe in order to use hex you need to do something like this:

cin >> hex >> x;
cout << hex << x; 

you can also replace hex with dec and oct etc.

like image 156
sean Avatar answered Oct 03 '22 23:10

sean


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.

like image 40
Karol D Avatar answered Oct 03 '22 23:10

Karol D