Reputation: 1553
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?
Upvotes: 21
Views: 43640
Reputation: 391
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.
Upvotes: 29
Reputation: 157
#include<iostream>
using namespace std;
int main()
{
int data[16];
cout << "enter the 16 hexadecimal numbers\n";
for(int i = 0;i < 16;i++)
{
if(cin >> hex >> data[i])
cout << "input worked\n";
else{
cin.clear();
cout << "invalid input\n";
}
}
}
Upvotes: 0
Reputation: 10497
Your code should read:
int x;
cin >> hex >> x;
By default cin
will expect any number read in to be decimal. Clearly, 0x1a
is not a valid decimal and so the conversion cannot take place. To get it to work we have to use the stream modifier hex
which prompts cin
to expect number conversion from hexadecimal rather than decimal.
The 0x
prefix is optional in this case so the input 10
would be read and stored as decimal 16.
Upvotes: 2
Reputation: 96810
Think of <<
and >>
when using std::cout/std::cin
like so:
std::cout << x
means get the value from x
std::cin >> x
means put the value into x
Notice the directions in which the operators are pointing. That should give you a hint as to what they do when using these functions.
The reason that you are getting 0 as a result and not 26 is because std::cin
will parse the all non numeric characters from your input. After all, x
is an int, it won't recognize 0x
as a part of a hexadecimal number. It would of had the same behavior if the input was 9x2
(the result would simply be 9
).
Upvotes: 3
Reputation: 530
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.
Upvotes: 39